iis服务器助手广告广告
返回顶部
首页 > 资讯 > 服务器 >unix编程创建前缀固定的临时文件代码分享
  • 186
分享到

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

前缀临时文件代码 2022-06-04 21:06:08 186人浏览 独家记忆
摘要

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

参数:
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);

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

--结束END--

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

本文链接: https://www.lsjlt.com/news/17929.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作