Ani*_*mj' 3 c++ fstream iostream file
我有以下代码
#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;
}
Run Code Online (Sandbox Code Playgroud)
test.txt
包含
hello world!
stackoverflow
Run Code Online (Sandbox Code Playgroud)
以上代码输出
hello world!
stackoverflow
Run Code Online (Sandbox Code Playgroud)
运行后代码stackexchange
不会追加到最后test.txt
.如何阅读然后写入文件?
纳瓦兹的评论是正确的.您的读循环迭代,直到fstream::operator bool
(of ofile
)返回false.因此,在循环之后,必须设置failbit或badbit.当循环尝试读取最后一次但只剩下EOF时,会设置failbit.这是完全正常的,但您必须在尝试再次使用流之前重置错误状态标志.
// ...
ofile.clear();
ofile << "stackexchnange" << endl;
Run Code Online (Sandbox Code Playgroud)
fstream 有两个位置:输入和输出。在您的情况下,当您打开文件时,它们都被设置为文件的开头。
所以你有4种方法:
tellp // returns the output position indicator
seekp // sets the output position indicator
tellg // returns the input position indicator
seekg // sets the input position indicator
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您可以使用以下行将输出位置设置为文件末尾
ofile.seekp(0, std::ios_base::end);
Run Code Online (Sandbox Code Playgroud)
PS 我错过了 ios::app 标志。我很抱歉。@Nawaz 的评论给出了正确的答案:阅读整个文件后,有必要调用
ofile.clear(); //cleanup error and eof flags
Run Code Online (Sandbox Code Playgroud)