简体   繁体   中英

How do you get the filename of a tempfile to use in 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?

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.

The question is how to generate a temporary file name . Neither mkstemp nor tmpfile provide the caller with a name, they return a file descriptor or file handle, respectively.

@garethm:

I believe that the function you're looking for is called tmpnam.

You should definitely not use tmpnam . It suffers from the race condition problem I mentioned in my answer: Between determining the name and opening it, another program may create the file or a symlink to it, which is a huge security hole.

The tmpnam man page specifically says not to use it, but to use mkstemp or tmpfile instead.

Absolutely: man mkstemp.

The man page has example usage.

不确定 C 库中的任何内容,但您可以在 shell 中使用mktemp执行此操作。

You should use the mkstemp() as this is the recommended function, but it returns a file descriptor, so once you have the descriptor get it's name:

int fd;
fd = mkstemp("hdrXXXXXX);
/* Read out the link to our file descriptor. */
sprintf(path, "/proc/self/fd/%d", fd);
memset(result, 0, sizeof(result));
readlink(path, result, sizeof(result)-1);

/* Print the result. */
printf("%s\n", result);

usually there's no need to actually make a named file; instead use the file descriptor path,

FILE *tmp=tmpfile();
char path[PATH_MAX+1]={0};
sprintf(path, "/dev/fd/%d", fileno(tmp));
printf("%s\n", path);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM