< cpp‎ | io‎ | c
Revision as of 18:37, 2 November 2012 by P12bot (Talk | contribs)

Defined in header <cstdio>
FILE* tmpfile();

Creates and opens a temporary file with unique auto-generated filename.

The file is opened as binary file for update (as by std::fopen with access mode "wb+"). At least TMP_MAX files may be opened during the lifetime of a program (this limit may be shared with std::tmpnam and may be further limited by FOPEN_MAX)

If the program closes the file, e.g. by executing std::fclose, the file is automatically deleted.

If the program terminates normally (by calling std::exit, returning from main, etc), all files that were opened by calling std::tmpfile are also automatically deleted.

If the program terminates abnormally, it is implementation-defined if these temporary files are deleted.




Return value

The associated file stream or NULL if an error has occurred


On some implementations (e.g. Linux), this function actually creates, opens, and immediately deletes the file from the file system: as long as an open file descriptor to a deleted file is held by a program, the file exists, but since it was deleted, its name does not appear in any directory, so that no other process can open it. Once the file descriptor is closed, the space occupied by the file is reclaimed by the filesystem.


#include <iostream>
#include <cstdio>
#include <cstdlib>
int main()
    FILE* tmpf = std::tmpfile();
    std::fputs("Hello, world", tmpf);
    char buf[6];
    std::fgets(buf, sizeof buf, tmpf);
    std::cout << buf << '\n';
    // Linux-specific method to display the tmpfile name
    std::system("ls -l /proc/self/fd/3");

Possible output:

lrwx------ 1 user group 64 Jun 27 00:28 /proc/self/fd/3 -> /tmp/tmpfXu58Zi (deleted)

See also

Template:cpp/io/c/dcl list tmpnam
C documentation for tmpfile