Load binary file using fstream

后端 未结 4 1913
遇见更好的自我
遇见更好的自我 2021-01-01 06:28

I\'m trying to load binary file using fstream in the following way:

#include 
#include 
#include 
#include         


        
4条回答
  •  Happy的楠姐
    2021-01-01 07:10

    You can reload operator>> to read integers properly. Of course all it will do is read() 4 bytes. But that's what all other operators>> are eventually doing anyway.

    Here is example (no error checking, assuming endianess is same as current compiler uses, etc)

    std::istream& operator>>(std::istream& in, uint32_t& data)
    {
        in.read(&data, sizeof(data));
        return in;
    }
    

    Tailor for your own flavor of integers (might have to read one byte at a time and shift assign them, look at the file in hex editor if you don't know byte order), add error checking, and you should be able to use your existing code.

    EDIT: ah, and yes, make sure this shadows provided stl operator that reads integer -- might have to derive your own class from the stream you are using and use that instead of std::istream& in, just so compiler knows who to check first.

提交回复
热议问题