c++qtoverwriteqfile

QFile/QDataStream writing on existing data


I have got a file which is let's say 8 bytes length. For example it looks like that:

22222222

Now, I read first let's say 5 bytes and changing them. For ex. to 11111

Finally, I want to write them ONTO EXCISTING DATA to the file, so I expect the file to look like that:

11111222

But I get only 11111, because file is erased. How can I disable erasing? (Maybe this question exists, but couldn`t find question like this one)


Solution

  • Depending on what you are exactly doing with the file, you might want to memory map it:

    QFile f("The file");
    f.open(QIODevice::ReadWrite);
    uchar *buffer = f.map(0, 5);
    
    // The following line will edit (both read from and write to)
    // the file without clearing it first:
    for (int i=0; i<5; ++i) buffer[i] -= 1;
    
    f.unmap(buffer);
    f.close();