OwlR
OwlR

Reputation: 451

c++ fstream read() function not working

Why my following code fails to read single integer from file? It displays "fail() reading" followed by "0".

On linux ubuntu gcc compiler.

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream fout2("int_data",ios::binary|ios::out);
    int a = 2;
    fout2.write((char*)&a,sizeof(a));
    int b=0;
    ifstream fin2("int_data",ios::binary|ios::in);
    fin2.read((char*)&b,sizeof(b));
    if(fin2.fail())
        cout << "fail() reading" << endl;
    cout << b << endl;
}

Upvotes: 0

Views: 1922

Answers (1)

Jonathan Mee
Jonathan Mee

Reputation: 38919

This could fail for a couple reasons:

  1. Your OS may be protecting you from opening a file that is currently opened for writing
  2. You may not have flushed your data to the file

You can solve both of these by using close before you construct fin2:

ofstream fout2("int_data", ios::binary);
const int a = 2;

fout2.write(reinterpret_cast<const char*>(&a), sizeof(a));
fout2.close();

int b = 0;
ifstream fin2("int_data", ios::binary);

if(!fin2.read(reinterpret_cast<char*>(&b), sizeof(b))) {
    cout << "fail() reading" << endl;
}
cout << b << endl;;

Live Example

Upvotes: 1

Related Questions