Search code examples
qtqfile

Writing an entire array to QFile


The QFile::write() documentation says:

Writes at most maxSize bytes of data from data to the device. Returns the number of bytes that were actually written, or -1 if an error occurred.

(Yes that's the entire documentation - unusually poor for Qt.)

This seems to imply that it is common for it not to write all of the data you pass. Does that mean I should call write() in a loop, passing in the remaining unwritten data until it has fully written it?

If so that seems like a pain. Is there some convenience function in Qt that will do it for me?


Solution

  • This seems to imply that it is common for it not to write all of the data you pass

    Common, no, but it is possible, which we'll see, below.

    Is there some convenience function in Qt that will do it for me?

    If you're writing a whole file, a better method would be to use QSaveFile, for "safely writing to files".

    As it states in the documentation for QSaveFile:

    QSaveFile automatically detects errors while writing, such as the full partition situation, where write() cannot write all the bytes.

    So a full partition would be one instance that could cause a QIODevice::write to fail to fully write data to disk. Disk failure, removal of a portable storage device or network drive during a write to those can also cause only partial data to be written.