如何在不关闭 C++ fstream 文件的情况下保存和读取它

How to save and also read c++ fstream file without closing it

我打开了一个读写模式的文件

使用以下语句

file.open(fileName, ios::in | ios::out | ios::trunc);

我在两种模式下打开文件的主要目的是同时读取和写入文件。

但是在我的代码场景中,

当我在写入文件后读取文件时,输出显示空白,这意味着, 没有保存我写的内容,因为我没有关闭它

并且我想在完成写入和读取操作后关闭文件

我在 Stack Overflow 中找到了解决方案,

使用flush()函数在不关闭的情况下保存文件

file.flush();

但是,问题是它不适用于我的情况

那么,如何在不关闭的情况下保存c++ fstream文件呢?

为了更好地理解,这是我的完整代码

#include <iostream>
#include <string>
#include <fstream>
using namespace std;


int main(int argc, char const *argv[])
{
    string fileName = "text.txt";

    fstream file;


    file.open(fileName, ios::in | ios::out | ios::trunc);

    if (file.is_open())
    {
        file << "I am a Programmer" << endl;
        file << "I love to play" << endl;
        file << "I love to work game and software development" << endl;
        file << "My id is: " << 1510176113 << endl;

        file.flush(); // not working 
    }
    else
    {
        cout << "can not open the file: " << fileName << endl;
    }

    if (file.is_open())
    {
        string line;

        while(file)
        {
            getline(file, line);

            cout << line << endl;
        }
    }
    else
    {
        cout << "can not read file: " << fileName << endl;
    }

    file.close();

    return 0;
}

在读取该文件之前,您需要确保将指向该文件的指针放在文件的开头。写入文件后,它将指向末尾。因此,您将无法阅读任何内容。

您需要在 file.flush() 之后但在开始读取之前的某处使用 file.seekg(0); 以将文件指针指向最开头。

更新

应该在没有冲洗的情况下工作。然而,这将取决于 std 库的实现。尽管如果不调用 flush() 恕我直言就无法正常工作,我会认为这是错误,但明确调用它并没有什么坏处。

其实,如果你想立即保存任何文件而不关闭文件,那么你可以简单地使用

file.flush();

但是如果你想在写入文件后不关闭而直接读取文件,你可以简单地使用

file.seekg(0);

实际上seekg()函数在开头重置了文件指针,为此,并不强制保存文件。所以,这与 flush() 函数无关

但如果你愿意,你可以两者都做