문제

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.

도움이 되었습니까?

해결책

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();

다른 팁

I agree with Daniel's answer if the file size remains small, but if the application keeps writing to the file and it becomes very large, you're reading the complete file in to memory.

In this situation, you could create a second file and copy the bytes from the first up until the insertion position. Then write the new bytes to the file before copying the rest of the data in the first file. So the steps involved would be: -

Open file1 for read
Open file2 for write
Copy file 1 to file2 until insertion point
Write new bytes to file2
Copy remaining bytes from file1 to file2
Close file handles
Delete file1
Rename file2 to file1's name.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top