【发布时间】:2018-10-07 16:04:31
【问题描述】:
我有这个小程序。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream f("file.txt", ios::out);
f << "Hello world!" << endl;
f.close();
fstream atEnd("file.txt", ios::out | ios::ate);
cout << "Position: " << atEnd.tellp() << endl;
atEnd << "You too" << endl;
atEnd.close();
return 0;
}
它应该打开文件,向其中写入一些内容,然后关闭它并在最后再次重新打开,因此应该在文件末尾附加文本“You too”。但位置始终为 0,内容被重写:https://www.onlinegdb.com/online_c++_compiler。为什么会这样?根据文档,ios::ate 应该在打开后立即搜索到流的末尾。
【问题讨论】:
-
考虑为此目的使用 ios_base::app (append) 标志,而不是 ios::ate