unix編程創(chuàng)建前綴固定的臨時文件代碼分享
參數:
pathname,存儲臨時文件的路徑文件名,需要手動free()掉。
dir,臨時文件的路徑,如果TMPDIR環(huán)境變量不為空,則此參數被忽略,轉而使用環(huán)境變量。
pfx,臨時文件名的前綴,只使用前5個字符。
注:
創(chuàng)建的臨時文件需要手動unlink()掉。
創(chuàng)建臨時文件的函數
int Make_temp_file(char **pathname,const char *dir,const char *pfx){
char *ptr,*tmp;
size_t len;
int fd;
debug_assert("Invalid pointer","Make_temp_file()",pathname);
/*前綴只能是多于5字符*/
if(pfx && (len=strlen(pfx))>0){
tmp=(char*)Malloc((len>5?5:len)+1);
strncpy(tmp,pfx,len>5?5:len);
}
else
tmp=NULL;
ptr=tempnam(dir,tmp);
if(tmp)free(tmp);
len=strlen(ptr);
tmp=(char*)Malloc(len+6+1);
if(snprintf(tmp,len+6+1,"%sXXXXXX",ptr)==-1)
err_sys(errno,"snprintf() error");
free(ptr);
fd=Mkstemp(tmp);
*pathname=tmp;
return fd;
}
測試程序
#include "wrap_ext.h"
int main(int argc,char **argv){
int fd;
char *path;
if(argc!=3)
err_quit(-1,"usage %s <dir> <prefix>",argv[0]);
fd=Make_temp_file(&path,argv[1][0]==' '?NULL:argv[1],argv[2][0]==' '?NULL:argv[2]);
err_msg("temporary file path:%s",path);
Close(fd);
Unlink(path);
free(path);
return EXIT_SUCCESS;
}
測試結果
root@U-SERVER:/home/apu/sysinfo# ./tmpfile " " " "
temporary file path:/tmp/fileq55hoF8swFfa
root@U-SERVER:/home/apu/sysinfo# ll /tmp/fileq55hoF8swFfa
ls: cannot access /tmp/fileq55hoF8swFfa: No such file or directory
root@U-SERVER:/home/apu/sysinfo# ./tmpfile " " tmp_
temporary file path:/tmp/tmp_0rzhqozlthxW
root@U-SERVER:/home/apu/sysinfo# ./tmpfile /home tmp_
temporary file path:/home/tmp_phzxvRrp33OL
相關文章
linux下安裝oracle后使用命令行啟動的方法 linux啟動oracle
這篇文章主要介紹了在linux下安裝oracle后使用命令啟動oracle的方法,大家參考使用吧2014-01-01

