Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

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.


  • Moderators

    @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


  • Qt Champions 2017

    @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. ;)



  • @m.sue Thanks a lot for answer me!

    I have tried to read as:

    int width;
    int height;

                infile.read((char*)(width), sizeof(uint32_t)*(2*1));
    

    But it fives me segmetation fault in "infile.read...."



  • This should work (if it compiles :-):

    infile.read((char*)(&width), sizeof(uint32_t));
    infile.read((char*)(&height), sizeof(uint32_t));
    

    -Michael.



  • @m.sue It works!! Thanks!



  • 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;
    

Log in to reply