Search code examples
qtqt4qt5qfileqbytearray

Qt: Insert QByteArray in a file at a certain position


Is it possible to insert a QByteArray on a certain position in a file? For example if I have a file that already has 100KB of data, is it possible to insert a QByteArray for example at position 20? And after that the file to be constructed of the sequence from 0KB to 20KB of data, then that QByteArray, and after that the sequence from 20KB to 100KB of data.


Solution

  • There no single function for doing it, but it can be done by just a few lines of code.

    Assuming data is a QByteArray with the data to be inserted into the file.

    QFile file("myFile");
    file.open(QIODevice::ReadWrite);
    QByteArray fileData(file.readAll());
    fileData.insert(20, data); // Insert at position 20, can be changed to whatever you need.
    file.seek(0);
    file.write(fileData);
    file.close();