Read binary data.
-
Hello.
First of all thanks a lot for reading this post and being able to help.I write a binary file like this:
myFile.write(reinterpret_cast<const char *>(&width), sizeof(uint32_t)); myFile.write(reinterpret_cast<const char *>(&height), sizeof(uint32_t)); myFile.write(reinterpret_cast<const char *>(&resx), sizeof(float)); myFile.write(reinterpret_cast<const char *>(&resy), sizeof(float)); myFile.write(reinterpret_cast<const char *>(&origx), sizeof(float)); myFile.write(reinterpret_cast<const char *>(&origy), sizeof(float)); ` Now I would like to read that binary file and get "width and height" in a int. How can I do that? just read the 2 first bytes? Thanks a lot!
-
Hi,
You will need to read the first 8 bytes as you save two 4 byte (uint32 = unsigned 32-bit) integers at the head of the file.
-Michael. -
@AlvaroS
whats the purpose of the binary file?
If you want to read it again using Qt, then simply use QDataStream which handles the correct sizes (reading and writing) for you. -
reinterpret_cast is the WORST way of serialising EVER!
You can use QDataStream the Qt way or just using standard C++ fstream. There is no justification EVER to use reinterpret_cast. it's just bad programming
-
@VRonin said in Read binary data.:
There is no justification EVER to use reinterpret_cast. it's just bad programming
There is, in some fringe cases, but I relate to the sentiment. ;)
-
This should work (if it compiles :-):
infile.read((char*)(&width), sizeof(uint32_t)); infile.read((char*)(&height), sizeof(uint32_t));
-Michael.
-
for whoever comes here, the correct way is:
Using Qt (myFile is QFile*)
// Write QDataStream writeStream(myFile); writeStream << width << height << resx<< resy<< origx<< origy; // Read QDataStream readStream(myFile); readStream>> width >> height >> resx>> resy>> origx>> origy;
2/9