Linux temporary files

Source: Internet
Author: User

In many cases, the program uses some temporary storage methods in the form of files.

You can use the tmpname function to generate a unique file name.

# Include <stdio. h>

Char * tmpname (char * s)

The tmpname function returns a valid file name that does not have the same name as any existing file name. If String S is not empty, the file name is also written to it. Subsequent call to tmpname

Will overwrite the static storage area that stores the returned values.

If you need to use a temporary file immediately, you can use the tmpfile function to open it while naming it. This is very important. Because another program may create

Tmpfile () completely avoids this situation.

# Include <stdio. h>

File * tmpfile (void );

Tmpfile () returns a file stream pointer pointing to a unique temporary file. This file is opened in read/write mode. When all references to a file are deleted, this temporary file will

Deleted.

If an error occurs, the tmpfile function returns a null pointer and sets the errno value.

#include <stdio.h>#include <stdlib.h>int main(){    char tmpname[L_tmpnam];    char *filename;     FILE *tmpfp;    filename = tmpnam(tmpname);    printf("Temporary file name is: %s\n", filename);    tmpfp = tmpfile();    if(tmpfp)        printf("Opened a temporary file OK\n");    else        perror("tmpfile");    exit(0);}

Another method of generating temporary file names for UNIX is to use the mktemp and mktemp functions.

# Include <stdlib. h>

Char * mktemp (char * template );

Int mkstemp (char * template );

The mktemp function creates a unique file name based on the given template. The template parameter must be a string ending with 6 x characters.

The mkstemp function is similar to tempfile (). It also creates and opens a temporary file. The file name generation method is the same as mktemp, but its return value is

The underlying file descriptor.

In the program, you should use the "Create and open" functions tmpfile and mkstemp instead of tmpname and mktemp functions.

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.