Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 488
  • Last Modified:

ifstream::operator>> problem

im trying to read width and height property of a BMP image file like:

    ifstream bmp(file_name.c_str(), ios::binary);
    if(!bmp) throw string("unable to open " + file_name + "!");
    unsigned int width( 0), height(0);  
    bmp.seekg(18);   //move to  width/height position
    bmp >> width;
    bmp >> height;
just nothing happens, though reading chars is okay. isnt ifstream::operator>> supposed to deal with ints also(like istream does)? dont want to use the ugly ifstream::read(...)

  • 2
1 Solution
>>>>    bmp >> width;

That statement would work with ASCII numbers but not with binary data. So i think, you have to use ugly read() ...
     bmp.read((char*)&width, sizeof(int));

Regards, Alex
Binary files often are read/written using structs. The struct representation in memory must exactly match to that of the binary data (you have to care about alignments; any new member variable should be allocated at a byte offset that is a multiple of 4 or 8 (depending on compiler settings); or you disable alignment by #pragma). Then, you could read data by record rather than by bytes. You also could handle different records or read whole (rest of) file to a byte array.

Regards, Alex

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now