parameter:
pathname, the path file name that stores the temporary file, needs to be manually removed from free().
dir, the path to the temporary file. If the TMPDIR environment variable is not empty, this parameter is ignored and instead uses the environment variable.
pfx, the prefix of temporary filenames, uses only the first 5 characters.
Note:
The created temporary files need to be manually unlink()ed.
Functions to create temporary files
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);
/*Prefix can only be more than 5 characters*/
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;
}
Testing procedures
#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;
}
Test results
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