unix编程创建前缀固定的临时文件代码分享

(编辑:jimmy 日期: 2024/10/5 浏览:2)

参数:
pathname,存储临时文件的路径文件名,需要手动free()掉。
dir,临时文件的路径,如果TMPDIR环境变量不为空,则此参数被忽略,转而使用环境变量。
pfx,临时文件名的前缀,只使用前5个字符。
注:
创建的临时文件需要手动unlink()掉。

创建临时文件的函数
复制代码 代码如下:
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

一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。