简体   繁体   中英

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

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

Before reading from that file you need to make sure to place the pointer to that file to the beginning of the file. After writing to the file it'll point to the end. Therefore you won't be able to read anything.

You need to use file.seekg(0); somewhere after the file.flush() but before starting to read to place the file pointer to the very beginning.

Update

This should work without the flush. However this will depend on the implementation of the std library. Although I'd consider this as bug if it doesn't work without calling flush() imho it does not hurt to call it explicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM