ifstream::operator>> problem

Posted on 2004-11-09
Last Modified: 2010-05-18
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(...)

Question by:podoboq
    LVL 39

    Accepted Solution

    >>>>    bmp >> width;

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

    Regards, Alex
    LVL 39

    Expert Comment

    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

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
    Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
    The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
    The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

    754 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now