Search code examples
c++filefstream

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


I opened a file both read and write mode

using the following statement

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

my main purpose for opening the file in both mode is, read and write the file at the same time.

But In my code scenario,

when I am reading the file after writing it, the ouput showing blank that means, it is not saving my writing contents because I am not closing it.

And I want to close the file after finishing both write and read the operation

I found a solution in Stack Overflow,

to use flush() function to save the file without closing

file.flush();

but, the problem is it's not working for my case

So, how can I save c++ fstream file without closing?

Here's my full code for better understanding

#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;
}

Solution

  • Actually, if you want to save any file immediately without closing the file, then you can simply use

    file.flush();
    

    But if you are want to read the file without closing just after writing it, you can simply use

    file.seekg(0);
    

    actually seekg() function resets the file pointer at the beginning, for this, it is not mandatory to save the file. so, this has nothing to with flush() function

    but you can do both if you want to