Linux temporary files

Source: Internet
Author: User

Note the usage of temporary files: files cannot be edited by multiple tasks at the same time.

Char * tmpnam (char * s) creates a file with different names from all existing files.

Problem: other programs can also open and edit files with the same name as the names returned by tmpnam.

Note: The file name is assumed to at least l_tmpnam (usually 20) characters long

This function can be called at least several thousand times in a single program.

 

File * tmpfile (void); this prevents the Same Name of the above file because it is created to open the file at the same time

The returned stream Pointer Points to a unique temporary file and opens the file when it is created. The file mode is readable and writable, and

Will be automatically deleted when all references to the file are closed.

Code:

# 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 );
}

Output:

Temporary File Name is:/tmp/filesua8ul
Opened a temporary file OK

The unix version provides the same functionality as tmpnam, Except t that you can specify

Template for the temporary file name, which gives you a little more control over

File Location and name

# Include <stdlib. h>

Char * mktemp (char * template );

Int mkstemp (char * template );

 

Conclusion: You should always use the "Create and open" function, such as tmpfile and mkstemp,

Rather than tmpnam 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.