我尝试将矩阵序列作为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 << "}";
}发布于 2020-07-14 19:13:21
这是因为ios_base::ate是一个附加标志,决定打开模式的“主要”标志是in、out和app。
[input.output]/2中列出了有效的开放模式标志组合。
由于您没有指定in、out或app,因此ofstream::open默认使用模式out,该模式等同于截断文件的"w"。
在与ios_base::in结合使用时,ios_base::ate对于对文件进行“尾随”非常有用。
对于附加到文件,有ios_base::app,它完全符合您的情况。
发布于 2020-07-14 20:00:54
std::ofstream::ate截断现有文件。你链接的问题的一个answers也提到了它,你必须将ate和in结合起来以避免截断。使用app不会让你玩搜索。
void write_nums()
{
std::ofstream out_file("test.txt", std::ofstream::ate | std::ofstream::in);
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 << "}";
}https://stackoverflow.com/questions/62893333
复制相似问题