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 :如果文件已存在,则会丢弃其内容。 如果指定了ios :: out,则隐含此模式,并且ios :: ate,ios :: app, 和ios:in未指定。
答案 0 :(得分:2)
您需要将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();
现在文本被附加到结尾但有什么区别:
正如我所说app不允许移动写指针但是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();
上面我们可以将写指针移动到我们想要的位置,而不是app。