Wais Kamal
Wais Kamal

Reputation: 6180

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?

Upvotes: 0

Views: 1267

Answers (3)

user17970898
user17970898

Reputation:

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;
}

Upvotes: 0

KamilCuk
KamilCuk

Reputation: 141483

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 }

Upvotes: 7

tomaszmi
tomaszmi

Reputation: 520

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

Upvotes: 1

Related Questions