c++ - 如何为临时文件创建 std::ofstream?

标签 c++ file file-io mkstemp

好的,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/

相关文章:

c# - 如何在 C# ASP.NET 中生成 .zip 文件并将其发送给用户?

java - 通过 ObjectOutputStream 发送文件然后将其保存在 Java 中?

c++ - 从对象C++中的文件读取内容时发生段错误

c++ - 使用 std::ofstream 仅重写前 30 个字符的方法?

c++ - 在 C++ 中访问过度分配的内存

c++ - 在 C++ 中显示图像及其元数据

python - 通过 csv 短路控制台输出

java - 如何从输入文件获取二维数组看起来像字段

c++ - 包含 emscripten header 时如何修复编译错误?

Linux 中的 C++ 可执行文件签名