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

SHA*_*AIN 5 c++ fstream file

我打开了文件的读写模式

使用以下语句

file.open(fileName, ios::in | ios::out | ios::trunc);
Run Code Online (Sandbox Code Playgroud)

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

但是在我的代码场景中

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

我想在完成读写操作后关闭文件

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

使用flush()函数保存文件而不关闭

file.flush();
Run Code Online (Sandbox Code Playgroud)

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

那么,如何在不关闭的情况下保存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;
}
Run Code Online (Sandbox Code Playgroud)

Naz*_*que 6

实际上,如果您要立即保存任何文件而不关闭文件,则只需使用

file.flush();
Run Code Online (Sandbox Code Playgroud)

但是,如果您想在写入文件后不关闭文件的情况下读取文件,则可以使用

file.seekg(0);
Run Code Online (Sandbox Code Playgroud)

实际上seekg()函数会在开始时重置文件指针,为此,保存文件不是强制性的。因此,与flush()函数无关

但如果您愿意,您可以同时做