Parameters:
Pathname, the path file name of the temporary file is stored, and the manual free () is required.
Dir, the path to the temporary file, if the TMPDIR environment variable is not empty, this parameter is ignored and the environment variable is used instead.
PFX, the prefix of the temporary filename, using only the first 5 characters.
Note:
Temporary files created need to be manually unlink () dropped.
Functions to create temporary files
Copy Code code as follows:
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;
}
Test program
Copy Code code as follows:
#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
Copy Code code as follows:
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