Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

file

fstream

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?

like image 946
M Imam Pratama Avatar asked Mar 04 '23 20:03

M Imam Pratama


1 Answers

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.

like image 85
Saket Sharad Avatar answered Mar 16 '23 11:03

Saket Sharad