好的,mkstemp
是在 POSIX 中创建临时文件的首选方式。
但它打开文件并返回一个int
,这是一个文件描述符。由此我只能创建一个 FILE*,而不是 std::ofstream
,我更喜欢在 C++ 中创建它。 (显然,在 AIX 和其他一些系统上,您可以从文件描述符创建 std::ofstream
,但是当我尝试这样做时,我的编译器会报错。)
我知道我可以使用 tmpnam
获得一个临时文件名,然后用它打开我自己的 ofstream,但由于竞争条件,这显然不安全,并导致编译器警告 (g++ v3.4 . 在 Linux 上):
warning: the use of `tmpnam' is dangerous, better use `mkstemp'
那么,是否有任何可移植的方式来创建 std::ofstream
到临时文件?
最佳答案
我已经完成了这个功能:
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <vector>
std::string open_temp(std::string path, std::ofstream& f) {
path += "/XXXXXX";
std::vector<char> dst_path(path.begin(), path.end());
dst_path.push_back('\0');
int fd = mkstemp(&dst_path[0]);
if(fd != -1) {
path.assign(dst_path.begin(), dst_path.end() - 1);
f.open(path.c_str(),
std::ios_base::trunc | std::ios_base::out);
close(fd);
}
return path;
}
int main() {
std::ofstream logfile;
open_temp("/tmp", logfile);
if(logfile.is_open()) {
logfile << "hello, dude" << std::endl;
}
}
您可能应该确保使用正确的文件创建掩码调用 umask(我更喜欢 0600)- mkstemp 的联机帮助页说文件模式创建掩码不是标准化的。它使用 mkstemp 将其参数修改为它使用的文件名这一事实。因此,我们打开它并关闭它打开的文件(因此,不要让它打开两次),留下一个连接到该文件的 ofstream。
关于c++ - 如何为临时文件创建 std::ofstream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/499636/