Search code examples
c++fstreamifstreamofstream

Reading from file right after Writing in it


I wanna write in file and then read from it and print the result

Here is my code

#include<iostream>
#include<fstream>
using namespace std;
int main(int argc,char* argv[]){

int x,y;
ofstream fd1(argv[1]);
ifstream fd2(argv[1]);
cin>>x;
fd1<<x;
fd2>>y;
cout<<"just read "<<y<<endl;
fd1.close();
fd2.close();
return 0;
}

What's wrong with it? I input 123 it outputs "just read -1078463800"


Solution

  • Even if you can open both in read & write, this write operation is buffered, which means that it may not be written to disk unless you flush the stream (or you close the file).

    Of course the code below works perfectly:

    #include<iostream>
    #include<fstream>
    using namespace std;
    int main(int argc,char* argv[]){
    
    int x,y;
    ofstream fd1(argv[1]);
    
    cin>>x;
    fd1<<x;
    
    
    fd1.close();
    
    ifstream fd2(argv[1]);
    if (fd2.good())
    {
       cout << "read OK" << endl;
    }
    fd2>>y;
    cout<<"just read "<<y<<endl;
    fd2.close();
    
    return 0;
    }