This问题询问 app
和 ate
之间的区别以及答案和 cppreference暗示唯一的区别是 app
意味着写光标在每次写操作之前放在文件的末尾,而 ate
意味着写光标放在仅在打开时文件末尾。
我实际看到的(在 VS 2012 中)是指定 ate
丢弃现有文件的内容,而 app
会不是(它将新内容附加到以前存在的内容)。换句话说,ate
似乎暗示了 trunc
。
以下语句将“Hello”附加到现有文件:
ofstream("trace.log", ios_base::out|ios_base::app) << "Hello\n";
但是下面的语句只用“Hello”替换了文件的内容:
ofstream("trace.log", ios_base::out|ios_base::ate) << "Hello\n";
VS 6.0 的 MSDN 文档暗示这不应该发生(但这句话似乎已在 Visual Studio 的更高版本中撤回):
ios::trunc: If the file already exists, its contents are discarded. This mode is implied if ios::out is specified, and ios::ate, ios::app, and ios:in are not specified.
最佳答案
您需要将 std::ios::in
与 std::ios::ate
组合,然后查找文件末尾并附加文本:
假设我有一个文件“data.txt”,其中包含这一行:
"Hello there how are you today? Ok fine thanx. you?"
现在我打开它:
1: std::ios::app:
std::ofstream out("data.txt", std::ios::app);
out.seekp(10); // I want to move the write pointer to position 10
out << "This line will be appended to the end of the file";
out.close();
结果不是我想要的:没有移动写指针,但只有文本始终附加到末尾。
2: std::ios::ate:
std::ofstream out2("data.txt", std::ios::ate);
out2 << "This line will be ate to the end of the file";
out2.close();
上面的结果不是我想要的,没有附加文本,但内容被截断了!
要解决这个问题,请结合使用 ate
和 in
:
std::ofstream out2("data.txt", std::ios::ate | std::ios::in);
out2 << "This line will be ate to the end of the file";
out2.close();
现在文本附加到末尾,但有什么区别:
正如我所说,应用程序不允许移动写入指针,但 ate 可以。
std::ofstream out2("data.txt", std::ios::ate | std::ios::in);
out2.seekp(5, std::ios::end); // add the content after the end with 5 positions.
out2 << "This line will be ate to the end of the file";
out2.close();
上面我们可以将写指针移动到我们想要的位置,而在应用程序中我们不能。
关于c++ - ofstream 开放模式 : ate vs app,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47014463/