UNIX programming create prefix fixed temporary file code share _linux Shell

Source: Internet
Author: User
Tags strlen

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.