如何在 C++ 中同时使用 `fstream` 写入和读取文件?

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

我正在尝试将一些文本写入文件,然后仅使用 1 个 fstream 对象读取它。

除了 read/write 的顺序不同,我的问题与 非常相似。他试图先阅读然后写作,而我试图先写作然后阅读。他的代码能读不能写,而我的代码能写不能读

我试过 他的问题,但它只适用于读写而不适用于写读。

这是我的代码:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    fstream fileObj("file.txt", ios::out|ios::in|ios::app);

    // write
    fileObj << "some text" << endl;

    // read
    string line;
    while (getline(fileObj, line))
        cout << line << endl;
}

代码成功地将 some text 写入 file.txt,但它没有从文件输出任何文本。但是,如果我不向文件写入文本(删除 fileObj << "some text" << endl;),代码将输出文件的所有文本。如何先写入再读取文件?

这里是写入和读取文件的简单示例。 希望对你有帮助。

  #include<fstream>
    using namespace std;
    int main ()
    {

        ofstream fout ("text.txt"); //write
        ifstream fin ("text.txt"); // read

        fout<<"some text";
        string line;
        while (fin>> line) {
            cout<<line;
        }

        return 0;
    }

这是因为你的文件流对象在写操作后已经到达了文件末尾。当您使用 getline(fileObj, line) 读取一行时,您位于文件末尾,因此您不会读取任何内容。

在开始读取文件之前,您可以使用fileObj.seekg(0, ios::beg)将文件流对象移动到文件的开头,您的读取操作将正常进行。

int main()
{
    fstream fileObj("file.txt", ios::out | ios::in | ios::app);

    // write
    fileObj << "some text" << endl;

    // Move stream object to beginning of the file
    fileObj.seekg(0, ios::beg);

    // read
    string line;
    while (getline(fileObj, line))
        cout << line << endl;

}

尽管此答案不符合您 "reading and writing a file simultaneously" 的要求,但请记住,文件在写入时很可能会被锁定。