使用ios:ate写入到流会覆盖现有文件

Writing to ofstream using ios::ate overwrites existing file

本文关键字:覆盖 文件 ios ate 使用      更新时间:2023-10-16

我正试图将一系列矩阵作为CSV附加到磁盘上,并发现使用ios:ate会覆盖以前创建的任何现有文件。为了通过简化模型来说明这个问题,对下面函数write_nums((的第二次调用会导致第一次调用中写入的任何数据丢失。有办法解决这个问题吗?

之前在流打开模式中给出的这个问题的解决方案:ate与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 << "}";
}

std::ofstream::ate截断现有文件。您链接的问题的一个答案也提到了这一点,您必须将atein结合起来以避免截断。使用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 << "}";
}
这是因为ios_base::ate是一个附加的标志;初级";确定打开模式的标志是inoutapp

[input.output]/2中列出了有效的打开模式标志组合。

由于未指定inoutapp,因此ofstream::open默认为模式out,相当于截断文件的"w"

CCD_ 15与CCD_;拖尾;文件。

对于附加到文件的ios_base::app,它与您的情况完全匹配。