0

i made this little code to read char by char the 120 first bytes of a binary file :

int main(){
string filename("kodim23.qoi");
ifstream image_file(filename); //open file
if (!image_file.is_open()) { //check if file is open
    cerr << "Could not open the file - '"
        << filename << "'" << endl;
    return EXIT_FAILURE;
}
for (int q = 0;q<120;q++) //read char by char and display them as int
{
    cout << q << " : ";
    cout << int(image_file.get()) << endl;
}
image_file.close(); //close file
return 0;
}

I get an expected output for q in range 0 to 114 and then just -1 forever (i tried to increase q it's always -1) : console output.

I tried to open the file with frhed (an hexadecimal editor) to check what happens at offset 115, but there is nothing weird : frhed output.

As you can see at offset 114 there is 0x54 (84), so my program is working as expected and then at offset 115 there is 0x1a (90) and my program output is -1...

Do you know what could be wrong ?

  • Unrelated: Wasted cast at `int(image_file.get())`. This overload of [`std::istream::get`](https://en.cppreference.com/w/cpp/io/basic_istream/get) returns an `int`. – user4581301 Jan 31 '23 at 21:14
  • 6
    Recommendation: Open the file as a binary file, eg. `ifstream image_file(filename, ios::binary);`. You'll get significantly fewer nasty surprises. Quite possibly including this one. – user4581301 Jan 31 '23 at 21:18
  • 1
    Unrelated: You nearly never need to/should `close()` an `*fstream` explicitly. It's automatically closed when the `*fstream` object goes out of scope. – Ted Lyngmo Jan 31 '23 at 21:20
  • 4
    @user4581301 is right. Platform? For hysterical reasons, 0x1A is treated as EOF on Windows when you open a file in text mode. – Paul Sanders Jan 31 '23 at 21:35
  • 1
    You could also just use [`qoi.h`](https://github.com/phoboslab/qoi/blob/master/qoi.h) and `qoi_read` the whole file into memory and look at it there. – Ted Lyngmo Jan 31 '23 at 21:36

0 Answers0