【发布时间】:2020-11-03 16:20:06
【问题描述】:
我正在尝试将一系列矩阵作为 CSV 附加到磁盘,并发现使用 ios::ate 会覆盖之前创建的任何现有文件。为了通过简化模型说明这个问题,第二次调用下面的函数 write_nums() 会导致第一次调用中写入的任何数据丢失。有没有办法解决这个问题?
之前在ofstream open modes: ate vs app 中给出的这个问题的解决方案似乎不是最优的,因为它只有在输出指向的文件已经存在的情况下才有效。
void write_nums()
{
std::ofstream out_file;
out_file.open("test.txt", std::ofstream::ate);
if (!out_file.good())
{
std::cerr << "Error while opening output file!" << '\n';
}
out_file.seekp(0, std::ios::end);
out_file << "{";
for (int i = 0; i < 10; ++i)
{
out_file << i << ',';
}
out_file.seekp(-1, std::ios::end);
out_file << "}";
}
【问题讨论】:
-
"只有在输出指向的文件已经存在的情况下才有效",不,带有
app标志的文件将在不存在时创建。