如何在c++中使用' fstream '同时读写文件

How to read and write in file with `fstream` simultaneously in c++?

本文关键字:fstream 读写 文件 c++      更新时间:2023-10-16

我有以下代码

#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的末尾。如何在文件中读取和写入?

Nawaz的评论是正确的。读取循环迭代,直到fstream::operator bool (ofile的)返回false。因此,在循环之后,必须设置failbit或badbit。当循环尝试最后一次读取,但只剩下EOF可读时,设置failbit。这是完全可以的,但是在尝试再次使用该流之前,您必须重置错误状态标志。

// ...
ofile.clear();
ofile << "stackexchnange" << endl;

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 

在您的例子中,您可以使用以下行将输出位置设置为文件

的末尾
ofile.seekp(0, std::ios_base::end);

PS我错过了ios::app标志。认错。@Nawaz的评论给出了正确的答案:在阅读了整个文件之后,有必要调用

ofile.clear(); //cleanup error and eof flags