带有tmpnam的C++文件IO永久临时文件
C++ File IO persistent temporary file with tmpnam
我正试图创建几个临时文件进行写入和读取,然后在程序完成后销毁。我看过tmpfile
,这会很好,但我也想知道那个文件的名称。我已经阅读了ofstream
的文档,但我认为我没有正确实现。我想做的事:
- 创建一个具有两个类型为
char xFile[64]
和char yFile[64]
的成员变量的类 - 在构造函数中,我放入:
std::tmpnam(xFile); std::tmpnam(yFile)
。这会将类似/y3s3
的c字符串分配到xFile中 - 我使用一种方法打开文件并添加一个字符串
- 每次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"将被替换为某个唯一字符串,该字符串将使文件名在目录中唯一。
相关文章:
- 为什么在读取文件大小时文件IO速度会发生变化
- C++中真正的异步文件 IO
- 用于 Windows 写入临时文件的 mkstemp() 实现
- Xcode OSX上的C++构建失败,出现多个错误文件IO..不可用:在macOS 10.15中引入
- 如何使用C 文件IO修复程序
- C++ 使用数字删除文件 io 行
- 我们是否需要互斥锁来执行多线程文件 IO
- C++带有字符串和浮点的文件 IO
- 多线程文件 IO 程序在线程数增加时行为不可预测
- 巴泽尔 无法创建临时文件
- 为什么将可执行文件重命名为临时文件的此代码段不能按预期工作?
- 无法使用 ofstream 写入 Windows 7 中的临时文件夹
- 如何写入临时文件夹
- 在C++程序中,IO/文件 IO 操作的优先级是否高于 CPU 操作
- Windows本身是否有虚拟或临时文件系统
- C++ 中的文件 IO 出错。在抛出 'std::length_error' 的实例后调用的终止 what(): basic_string::调整大小
- C/C++:在不使用临时文件的情况下压缩(gz)数据
- 写入临时文件
- 删除临时文件夹的内容
- 带有tmpnam的C++文件IO永久临时文件