How can I read a single byte from a binary stream?
I have a binary file which I would like to process one byte at a time. This is what I have for reading the first character of the file:
ifstream file("input.dat", ios::binary);
unsigned char c;
file >> c;
However, when I step through this code with a debugger, c
always has the value 0x00
although the first (and only) character of the file is 0x0A
. In fact, any other character is also totally ignored.
How do I read individual bytes from this file?
Solution 1:
Use std::istream::get
or std::istream::read
.
char c;
if (!file.get(c)) { error }
int c = file.get();
if (c == EOF) { error }
char c;
if (!file.read(&c, 1)) { error }
And finally:
unsigned char c;
if (!file.read(reinterpret_cast<char*>(&c), 1)) { error }