带有tmpnam的C++文件IO永久临时文件

C++ File IO persistent temporary file with tmpnam

本文关键字:临时文件 IO 文件 tmpnam C++ 带有      更新时间:2023-10-16

我正试图创建几个临时文件进行写入和读取,然后在程序完成后销毁。我看过tmpfile,这会很好,但我也想知道那个文件的名称。我已经阅读了ofstream的文档,但我认为我没有正确实现。我想做的事:

  1. 创建一个具有两个类型为char xFile[64]char yFile[64]的成员变量的类
  2. 在构造函数中,我放入:std::tmpnam(xFile); std::tmpnam(yFile)。这会将类似/y3s3的c字符串分配到xFile中
  3. 我使用一种方法打开文件并添加一个字符串
  4. 每次xFile.good()的计算结果都为false

关于第3点,我写了一些类似的东西

void filemng::makeXCopy (std::string text) {
    // actually I've tried fsteam and ifstream as well, shot in the dark
    std::ofstream xfile(xFile, std::ofstream::out); 
    if(!xfile.good()) {
        std::cerr << "Failed to open xFile.n";
    }
}

当然,当我运行它时,我会看到"打开xFile失败"。我只是看不出我在这里做错了什么。

这里有一个使用mkstemp:的例子

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
    char name[255] = "/tmp/mytempfile_XXXXXX";
    int fd = mkstemp(name);
    if (fd > 0) {
        printf("Created %sn", name);
        write(fd, "some dataan", strlen("some dataan"));
        close(fd);
    } else {
        printf("Failed n");
    }
    return 0;
}

请注意,传递给mkstmp的字符串中的"xxxxxx"将被替换为某个唯一字符串,该字符串将使文件名在目录中唯一。