Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a temporary file name?

I've seen some posts relating to my question, but none that address it completely. I need to create a file in the standard temporary directory and after I'm done writing to it, move it to a different location. The idea is that the file is considered temporary while being downloaded and permanent after downloading completes.

I'm attempting this by calling either mkstemp or tmpfile, then rename after I'm done writing to it. However, I need the full path of the file to call rename, and apparently getting the file name from a file descriptor (returned by mkstemp) or FILE * (returned by tmpfile) is no trivial process. It can be done, but it's not elegant.

Is there a system call that will create a temporary file and provide me with the name? I know about mktemp and related calls, but they either aren't guaranteed to be unique or are deprecated. Or perhaps there is a better way to accomplish creating, writing to, and moving temporary files.

like image 578
jorgander Avatar asked Aug 17 '12 15:08

jorgander


People also ask

How do I find the temporary file name?

To view and delete temp files, open the Start menu and type %temp% in the Search field. In Windows XP and prior, click the Run option in the Start menu and type %temp% in the Run field. Press Enter and a Temp folder should open.

How do I create a tmp 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.

What are temporary files example?

A temporary file is a file that is created to temporarily store information in order to free memory for other purposes, or to act as a safety net to prevent data loss when a program performs certain functions. For example, Word determines automatically where and when it needs to create temporary files.

How do you name a temp file in Python?

In Python, when you need to create a temporary file with a filename associated to it on disk, NamedTemporaryFile function in the tempfile module is the goto function.


1 Answers

It looks like mkstemp is actually the way to go.

int fd;
char name[] = "/tmp/fileXXXXXX";
fd = mkstemp(name);
/* Check fd. */

After this call you have a valid descriptor in fd and the name of the associated file in name.

like image 112
cnicutar Avatar answered Sep 22 '22 16:09

cnicutar