M Imam Pratama
M Imam Pratama

Reputation: 1279

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

I'm trying to write some text to a file and then read it using only 1 fstream object.

My question is very similar to this question except for the order of the read/write. He is trying to read first and then write, while I'm trying to write first and then read. His code was able to read but did not write, while my code is able to write but not read.

I've tried the solution from his question but it only works for read-write not write-read.

Here is my code:

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

The code writes some text to file.txt successfully but it doesn't output any text from the file. However, if I don't write text to the file (remove fileObj << "some text" << endl;), the code will output all text of the file. How to write first and then read the file?

Upvotes: 4

Views: 1843

Answers (2)

Saket Sharad
Saket Sharad

Reputation: 410

This is because your file stream object has already reached the end of the file after the write operation. When you use getline(fileObj, line) to read a line, you are at the end of the file and so you don't read anything.

Before beginning to read the file, you can use fileObj.seekg(0, ios::beg) to move the file stream object to the beginning of the file and your read operation will work fine.

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;

}

Although this answer doesn't qualify for your requirement of "reading and writing a file simultaneously", keep in mind that the file will most likely be locked while being written to.

Upvotes: 7

YWILLS
YWILLS

Reputation: 136

Here the simple example to write and read the file. Hope it will help you.

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

Upvotes: -1

Related Questions