Search code examples
c++filefstreamifstreamofstream

Why I can't write data from a file to a string, after I added some information to file using an ofstream variable?


I am trying to write and read information from the same file, but I don't know actually how to do that and why it doesn't work.

When I compile the code, the string that I expect to be filled with information from the file, actually doesn't get filled.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;


int main()
{
    string str;
    ifstream fin("Asort.txt");
    ofstream fout("Asort.txt");

    fout << "hello world";  

    getline(fin, str);
    cout << str;
}

Solution

  • The problem is the location of the "cursor" (thus: the marker) after the statement:

    fout << "hello world";
    

    Illustration:

     #include <iostream>
    #include <fstream>
    #include <string>
    
    using namespace std;
    
    
    int main()
    {
        string str;
        ifstream fin("Asort.txt");
        ofstream fout("Asort.txt");
    
        fout << "hello world";  //output to cout this statement(fout.tellp()) to see where the marker is at this point in the stream
        fout.seekp(0);   //reset the marker in the fout stream to the beginning
        getline(fin, str);
        cout << str;
    }
    

    The cursor is now at the end of the stream. So you have to use: fout.seekp(0); to get it to the beginning so that the fin can start reading from the beginning of the stream.