Okay, mkstemp
is the preferred way to create a temp file in POSIX.
But it opens the file and returns an int
, which is a file descriptor. From that I can only create a FILE*, but not an std::ofstream
, which I would prefer in C++. (Apparently, on AIX and some other systems, you can create an std::ofstream
from a file descriptor, but my compiler complains when I try that.)
I know I could get a temp file name with tmpnam
and then open my own ofstream with it, but that's apparently unsafe due to race conditions, and results in a compiler warning (g++ v3.4. on Linux):
warning: the use of `tmpnam' is dangerous, better use `mkstemp'
So, is there any portable way to create an std::ofstream
to a temp file?
I've done this function:
You should probably make sure to call umask with a proper file creation mask (I would prefer 0600)- the manpage for mkstemp says that the file mode creation mask is not standardized. It uses the fact that mkstemp modifies its argument to the filename that it uses. So, we open it and close the file it opened (so, to not have it opened twice), being left with a ofstream that is connected to that file.
This code works for me with GCC/libstdc++6 4.8.4 and Clang 3.9 as well. Thanks to the other replies as well which were helpful to me.
Maybe this will work:
I haven't tried it, but you can check.
I think this should work:
EDIT: Well, this might not be portable. If you can't use attach and can't create a ofstream directly from a file descriptor, then you have to do this:
As mkstemp already creates the file for you, race condition should not be a problem here.