1

是否可以QByteArray在文件中的某个位置插入a?例如,如果我有一个已经有 100KB 数据的文件,是否可以QByteArray在位置 20 处插入一个示例?之后要构建的文件是从 0KB 到 20KB 的数据序列,然后是QByteArray,然后是从 20KB 到 100KB 的数据序列。

4

2 回答 2

3

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();
于 2013-07-10T21:06:06.837 回答
1

如果文件大小仍然很小,我同意丹尼尔的回答,但是如果应用程序继续写入文件并且文件变得非常大,那么您正在将完整的文件读入内存。

在这种情况下,您可以创建第二个文件并将字节从第一个文件复制到插入位置。然后在复制第一个文件中的其余数据之前将新字节写入文件。所以所涉及的步骤是: -

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.
于 2013-07-11T07:48:01.230 回答