我要将一系列矩阵作为CSV附加到磁盘上,并发现使用ios::ate会覆盖之前创建的任何现有文件。为了通过一个简化的模型说明这个问题,下面的write_nums()函数的第二次调用会导致丢失在第一次调用中写入的任何数据。是否有方法可以修复这个问题?
先前在ofstream open modes: ate vs app中给出的解决此问题的方法似乎不太理想,因为它只适用于输出所定向的文件已经存在的情况。
先前在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
标志,则会在文件不存在时创建该文件。 - anastaciu