我有以下代码
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(void) {
fstream ofile;
ofile.open("test.txt", ios::in | ios::out | ios::app);
for(string line; getline(ofile, line) ; ) {
cout << line << endl;
}
ofile << "stackexchnange" << endl;
ofile.close();
return 0;
}
test.txt
包含
hello world!
stackoverflow
以上代码输出
hello world!
stackoverflow
运行代码后stackexchange
没有附加在末尾test.txt
。如何读取文件然后写入文件?
纳瓦兹的评论是正确的。你的读循环迭代直到fstream::operator bool
(of ofile
) 返回 false。因此,在循环之后,必须设置failbit 或badbit。当循环尝试最后一次读取但只剩下 EOF 时,将设置失败位。这是完全可以的,但是您必须在尝试再次使用该流之前重置错误状态标志。
// ...
ofile.clear();
ofile << "stackexchnange" << endl;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)