这问题询问了app和ate之间的区别,答案和优先选择都意味着唯一的区别是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中被撤回了):
ios::trunc:如果文件已经存在,则其内容将被丢弃。如果指定了ios::out,而未指定ios::ate、ios::app和ios:in,则暗示此模式。
发布于 2017-10-30 12:17:49
您需要将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();在上面,我们可以移动写指针到我们想要的位置,而对于app,我们不能。
https://stackoverflow.com/questions/47014463
复制相似问题