How to read binary file



  • Hi,

    I'm trying to read a file as a binary, byte-by-byte, and strangely nothing seems to work with QFile. This code doesn't work but I 've also tried data streams and readAll(). Every time it gets truncated.

    @
    QFile file(fileName);
    char* temp;
    //int i;

    if (!file.open(QIODevice::ReadOnly)) {       
        return ;
    }
    
    temp = new char [file.size()];
    file.read(temp,file.size());
    
    file.close();
    QByteArray blob(temp);
    
    qDebug() << file.size() << endl;
    qDebug() << "----------------------------" << endl;
    qDebug() << blob << endl;
    qDebug() << "----------------------------" << endl;
    qDebug() << file.error() << endl;
    

    @

    I keep getting something like this

    @
    89989


    "ÿØÿà"


    0
    @

    It works with text files but I want it to work with all files, eg. jpg,png,pdf etc.

    I don't care about the file format. I just want a binary copy.


  • Moderators

    Why the temp?

    @
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly)) return;
    QByteArray blob = file.readAll();
    @

    should get you the contents of the file into your blob. That is what you were doing as well but without the unnecessary char array.

    Your code fails in line 13 where the blob is constructed from the temp char array. The constructor you are using is meant to "adopt" a char *, so it copies all the data starting at temp[0] up to the first 0 byte found. As you probably know a 0 byte signifies the end of a string with C character arrays.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.