如何创建一个std :: ofstream到一个临时文件? [英] How to create a std::ofstream to a temp file?
问题描述
好的, mkstemp
是在POSIX中创建临时文件的首选方法。
Okay, mkstemp
is the preferred way to create a temp file in POSIX.
但它打开文件并返回一个 int
,这是一个文件描述符。从那里我只能创建一个FILE *,但不是一个 std :: ofstream
,我想在C + +。 (显然,在AIX和其他一些系统上,你可以从文件描述符创建一个 std :: ofstream
,但是当我尝试这个时,我的编译器抱怨。)
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.)
我知道我可以用 tmpnam
获得一个临时文件名,然后打开我自己的stream,但是这显然是不安全的,因为竞争条件,并导致编译器警告(g ++ v3.4。在Linux上):
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'
c $ c> std :: ofstream 到临时文件?
So, is there any portable way to create an std::ofstream
to a temp file?
推荐答案
:
char *tmpname = strdup("/tmp/tmpfileXXXXXX");
ofstream f;
int fd = mkstemp(tmpname);
f.attach(fd);
编辑:这可能不是便携式的。如果你不能使用attach并且不能直接从文件描述符创建一个stream,那么你必须这样做:
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:
char *tmpname = strdup("/tmp/tmpfileXXXXXX");
mkstemp(tmpname);
ofstream f(tmpname);
由于mkstemp 已经为您建立档案,这里有一个问题。
As mkstemp already creates the file for you, race condition should not be a problem here.
这篇关于如何创建一个std :: ofstream到一个临时文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!