c++libstdc++mkstemp

What is the C++ standard library equivalent for mkstemp?


I am transitioning a program that uses temporary files from POSIX FILE to C++ standard library iostreams. What's the correct alternative to mkstemp?


Solution

  • There is no portable C++ way to do it. You need to create a file (which is done automatically when opening a file for writing using an ofstream) and then remove it again when you're finished with the file (using the C library function remove). But you can use tmpnam to generate a name for the file:

    #include <fstream>
    #include <cstdio>
    
    char filename[L_tmpnam];
    std::tmpnam(filename);
    std::fstream file(filename);
    ...
    std::remove(filename);   //after closing, of course, either by destruction of file or by calling file.close()