Search code examples
pythonc++filestreambinary

reading a binary file in c++ just like in python


I want to read a file in binary mode in c++. Initially i was using python to do the same when i read the same file using python i got the result b'\xe0\xa4\xb5\xe0\xa4\xbe\xe0\xa4\xb9' which when converted to INT resulted in 224 164 181 224 164 190 224 164 185 and i am able to notice that all these INTs are always in the range [0,255].

I want to do the same thing in c++ but am unabale to do the same I have tried a lot of diffrent tricks but the best i could get was c++ giving negative integers.


#include <iostream>
#include <io.h>
#include <fcntl.h>
#include <fstream>
#include <stdio.h>

int main()
{
    std::fstream file("a.txt", std::ios::out | std::ios::in | std::ios::binary);
    file.seekg(0, std::ios::end);
    int size = file.tellg();
    char ch;
    std::string text;
    std::cout << "Size = " << size << std::endl;
    file.seekg(0, std::ios::beg);
    char x;
    file.read((&x), 1);
    std::cout << static_cast<int>(x) << std::endl;
    return 0;
}

please ignore the #include i have used way lot of them.

OUTPUT

Size = 9
-32

Solution

  • As mentioned in the comments, the issue here is that char by default, is signed - meaning it takes values in the range [-128, 127]. This was, 224 will roll over to the negative end and become -32.
    You should use an unsigned char, which will make the range [0, 255].

    #include <iostream>
    #include <io.h>
    #include <fcntl.h>
    #include <fstream>
    #include <stdio.h>
    
    int main()
    {
        std::fstream file("a.txt", std::ios::out | std::ios::in | std::ios::binary);
        file.seekg(0, std::ios::end);
        int size = file.tellg();
        unsigned char ch;
        std::string text;
        std::cout << "Size = " << size << std::endl;
        file.seekg(0, std::ios::beg);
        unsigned char x;
        file.read((&x), 1);
        std::cout << static_cast<int>(x) << std::endl;
        return 0;
    }