[comp.lang.c++] Sucking in a mixture of int's and unsigned char's

kyt@cs.columbia.edu (Kok-Yong Tan) (05/13/91)

I'm trying to read in image data from a file in IMPROC format: the first 8
bytes are read in as two int's (the width and height of the image) and the rest
of the file consists of  width * height unsigned char's.

I've declared the following :

	ifstream InBuf(FileName, ios::nocreate);
	int Width;
	int Height;

and when I try to extract the first 8 bytes with:

	InBuf >> Width;
	InBuf >> Height;

I keep getting zeros when I know that it should be a 32 x 32 image and this
data is encoded in the first 8 bytes of the file.  I notice that 

	InBuf >> DataBuffer[Index]; // DataBuffer is declared as an array of
				    // unsigned char.

seems to work fine.  Since operator >> (int&) is defined, I would've thought
that the "InBuf >> Width" and "InBuff >> Height" would work similarly.  What
did I do wrong?  Thanks for any help.

 


--
Kok-Yong Tan can be reached at:      | "Labra lege."
InterNet: kyt@cunixa.cc.columbia.edu |	     - George Bush, if he were Caesar
CompuServe: 75046,256                | Everything that can possibly be 
America Online: lallang              | disclaimed is hereby disclaimed.

steve@taumet.com (Stephen Clamage) (05/15/91)

kyt@cs.columbia.edu (Kok-Yong Tan) writes:

>I'm trying to read in image data from a file in IMPROC format: the first 8
>bytes are read in as two int's (the width and height of the image) and the rest
>of the file consists of  width * height unsigned char's.

>I've declared the following :

>	ifstream InBuf(FileName, ios::nocreate);
>	int Width;
>	int Height;

>and when I try to extract the first 8 bytes with:

>	InBuf >> Width;
>	InBuf >> Height;

>I keep getting zeros ...

The problem is that the stream I/O functions expect to do conversions
to and from text files.  When you write
	InBuf >> Width;
the stream functions expect to find text representing an integral value,
not an integer itself.  If the first byte in the file does not correspond
to the representation of a CHARACTER between '0' and '9', that byte
will never be read, and the variable will have a zero value.  If you
check the stream state after the attempted read, you will find it
in the 'failed' state.

You can use read() to read n chars at a time into a char array, or use
get() to get one char at a time and build up the integer values.

It would probably be simpler just to use C standard I/O, since the
iostreams carry a lot of overhead when you just want to read binary
data from a file.  Your C++ implementation should support
	#include <stdio.h>
Check the documentation.
-- 

Steve Clamage, TauMetric Corp, steve@taumet.com