-3

Probably, I don't know something about ifstream. I have binary file : 0604 0204 0a02.

std::ifstream input(input_filename, std::ios::binary);
unsigned char cmd;
unsigned char type;
while (!input.eof()) {
    input >> cmd;
    input >> type;
    std::cout << static_cast<int>(cmd) << " " << (int)type << "\n";
}

And result of this code:

6 4
2 4
2 0

What is going wrong?

2 Answers2

2

operator >> is skipping white space. You need to call

while(input.read(&cmd, 1) && input.read(&type, 1)) {}

or

while(input >> std::noskipws >> cmd >> std::noskipws >> type) {}

Also please note the changed error checking (just casting the stream to bool).

Werner Henze
  • 16,404
  • 12
  • 44
  • 69
0

There are two problems here.

  1. 0x0A is an ASCII newline, and you're using formatted extraction. That's why your 10 is "skipped" and the 2 extracted instead.

    Use .get(), not >>

  2. You're using .eof(), which doesn't check for extraction errors, and checks only after you extract, so you're getting "extra" bad data past the end of your actual read (the 0 is nonsense). Don't use while (!stream.eof()) in a loop (usually).

Fixed code:

#include <fstream>
#include <iostream>

int main()
{
    std::ifstream input(input_filename, std::ios::binary);
    while (true)
    {
        const unsigned char cmd = input.get();
        const unsigned char type = input.get();

        if (!input)
            break;

        std::cout << static_cast<int>(cmd) << " " << (int)type << "\n";
    }
}

/*
g++ -std=c++17 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
6 4
2 4
10 2
*/

live demo

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35