Q: 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?

A: 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 }


A: 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");
}


A: Here you are:
#include <fstream>
#include <iostream>
#include <iterator>

int main() {
    std::ifstream is("in.dat", std::ios::binary);
    if (!is) {
        std::cout << "Unable to open file!\n";
    }
    for (std::istreambuf_iterator<char> beg(is), end; beg != end; ++beg) {
        // ...
    }
    return 0;
}

