Search code examples
c++qtread-writeqfile

Ensure all the bytes are properly written to file


Is it possible to check if all the bytes are actually being written on a QFile or not? Currently this is all I have

QFile f(name);
if (f.open(QIODevice::WriteOnly)){
     f.write(bytes);
}

bytes has a size of 1MB and there are times when the entire chunk is not written to file, hence I end up getting a corrupted file.


Solution

  • What you are looking for is a checksum with which you can check the integrity of your data. What you want to do here is use qChecksum like this:

    QFile f(name);
    if (f.open(QIODevice::ReadWrite)) {
         f.write(bytes);
    }
    
    quint16 fileCheckSum = qChecksum(bytes.data(), bytes.length());
    
    if (f.open(QIODevice::ReadWrite)) {
        QByteArray writtenBytes = f.readAll();
    
        quint16 writtenBytesCheckSum = qChecksum(writtenBytes .data(), writtenBytes .length());
    
        if(fileCheckSum == writtenBytesCheckSum)
        {
            qDebug() << "File is valid.";
        }
        else
        {
            qDebug() << "File is corrupt.";
        }
    }
    

    I haven't compiled the code but it should work. If it doesn't I'll be more specific with an example.