On Apr 25, 4:37 pm, sri <srinivasarao_mot...@yahoo.comwrote:
I think the following question is related to this group that is why I
am posting
The question is:
I am reading bytes from binary file. At a particular position the byte
value is "FF".
I am reading the byte as follows :
std::basic_ifstream<unsigned charin("somefile.bin",std::ios::in |
std::ios::binary);
Note that this may or may not compile, and if it compiles, the
behavior of the stream will be implementation defined. For all
intents and purposes, you should forget that the templates
exist, and just use istream or wistream.
unsigned int wData = 0;
unsigned long wPosition = 0x1C8L;
in.seekg(wPosition,std::ios::beg);
//the following statement gives wData value is zero instead "FF"
//read operation is failing
in.read(reinterpret_cast<unsigned char*>(&wData),1);
//but following statement gives wData value is "FF"
in.read(reinterpret_cast<char*>(&wData),1);
what is going wrong?
Well, if you were using ifstream, both of those read statements
would result in undefined behavior. You can't just read one
byte of an unsigned int, and expect to get anything reasonable.
If you're reading binary data, and want reading a single byte
containing 0xFF to set an unsigned int to this value, just using
istream::get() should work. (You'll probably want to assign the
results to an int first, to check for EOF, and then assign the
int to an unsigned int.)
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34