Home > Enterprise >  How can I read a single byte from a binary stream?
How can I read a single byte from a binary stream?

Time:01-23

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?

CodePudding user response:

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 }

CodePudding user response:

Please make sure that the file exists. You do not check any error prior to reading from the stream. You could for instance:

ifstream file("input.dat", ios::binary);
if(!file.is_open())
{
  throw std::runtime_error("invalid path");
}
  •  Tags:  
  • Related