Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the filename of a tempfile to use in Linux?

Tags:

c

linux

Let's say I'm creating a program in C that needs to use a tempfile. Creating an ad hoc tempfile in /tmp is probably not a good idea. Is there a function or OS call to supply me with a tempfile name so that I can begin to write and read from it?

like image 728
andrewrk Avatar asked Aug 27 '08 07:08

andrewrk


People also ask

What is file temp name?

Alternatively referred to as a foo file, a temporary file or temp file is a file created to hold information while a file's being created or modified. After the program is closed, the temporary file is deleted.

How do I create a tmp file in Linux?

The tmpfile function creates a temporary file and returns a file pointer. The mkstemp function creates a temporary file and returns a file descriptor. The mkdtemp function creates a temporary directory. The mktemp command is for creating a temporary file or directory from the shell.

How do I create a temp file?

To create and use a temporary fileThe application opens the user-provided source text file by using CreateFile. The application retrieves a temporary file path and file name by using the GetTempPath and GetTempFileName functions, and then uses CreateFile to create the temporary file.


1 Answers

You can use the mkstemp(3) function for this purpose. Another alternative is the tmpfile(3) function. Which one of them you choose depends on whether you want the file to be opened as a C library file stream (which tmpfile does), or a direct file descriptor (mkstemp). The tmpfile function also deletes the file automatically when you program finishes.

The advantage of using these functions is that they avoid race conditions between determining the unique filename and creating the file -- so that two programs won't try to create the same file at the same time, for example.

See the man pages for both functions for more details.

like image 179
gavrie Avatar answered Oct 27 '22 03:10

gavrie