使用ios:ate写入到流会覆盖现有文件
Writing to ofstream using ios::ate overwrites existing file
我正试图将一系列矩阵作为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
截断现有文件。您链接的问题的一个答案也提到了这一点,您必须将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 << "}";
}
ios_base::ate
是一个附加的标志;初级";确定打开模式的标志是in
、out
和app
。
[input.output]/2中列出了有效的打开模式标志组合。
由于未指定in
、out
或app
,因此ofstream::open
默认为模式out
,相当于截断文件的"w"
。
CCD_ 15与CCD_;拖尾;文件。
对于附加到文件的ios_base::app
,它与您的情况完全匹配。
相关文章:
- 使用ios:ate写入到流会覆盖现有文件
- 如何在 c++ 中覆盖相同的文本文件
- 每个文件(理想情况下是每个部分)的 clang 格式样式覆盖
- C++删除或覆盖文件中的现有信息
- 使用 tellg() 和 seekp() 覆盖文件
- 如何用CPP中的地图内容覆盖文件
- 为什么Visual C++中的“我的语言”翻译器程序不用翻译就覆盖文件
- 是否有任何方法可以仅在覆盖文件的情况下禁用DisplayAlerts
- 使用c++覆盖文件中的文本
- C++流覆盖文件
- 通过覆盖文件"Updating"文件中的行
- 在 C++ 中覆盖文件(不追加)
- C++ 覆盖文件数据
- 如何不覆盖文件,C++日志记录
- 如何使用C ++覆盖文件中的特定数据
- 我正在尝试以二进制写入一些文件,我需要覆盖文件内容,如何覆盖而不是插入
- 在不存在文件损坏风险的情况下覆盖文件
- Ofstream在多次执行时覆盖文件内容
- C++只覆盖文件的一段
- 如何在不关闭文件的情况下覆盖文件