简体   繁体   English

Qt-读取包含多个NULL字符的文件

[英]Qt - Reading file containing multiple NULL characters

I have gotten a file, which contains multiple NULL charactes /0 in a line. 我得到了一个文件,该文件在一行中包含多个NULL特征/0 My goal was to load the file and replace the /0 with something else, but I experience some problems doing that. 我的目标是加载文件并将/0替换为其他文件,但这样做时遇到了一些问题。

Qt stops reading the file, after it get's to the point, where the NULL character appears. 在到达NULL字符的位置后,Qt停止读取文件。

Code: 码:

QTextStream fileContent;
QFile file(pendingFile);
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
    fileContent.append(file.readAll());
}

File: 文件:

Text
Text
Text /x00/x00/x00/x00/x00/x00/x00

More Text

I am currently using Qt 5.9.1 and develop with VS2017. 我目前正在使用Qt 5.9.1并使用VS2017进行开发。

Read the file with as QDataStream 使用QDataStream读取文件

QFile file("raw.dat");
file.open(QIODevice::ReadOnly);
QDataStream fileStream(&file);

qint64 fileSize = file.size();

QByteArray data(fileSize, '\0');
fileStream.readRawData(data.data(), fileSize)

In the ByteArray you can replace all \\0 elements. 在ByteArray中,您可以替换所有\\ 0元素。

Update (comments, look at underscore_d 's answer): 更新(评论,请看underscore_d的答案):

data.replace('\0','_');
QString dataString(data);

The problem is not that QFile stops reading at NUL (ie '\\0' , not the NULL macro), but rather that QTextStream considers a NUL to mean end-of-string and thus stops append() ing after the first NUL it encounters. 问题不在于QFileNUL处停止读取(即'\\0' ,而不是NULL宏),而是QTextStream认为NUL表示字符串结尾,因此在遇到第一个NUL之后停止了append()

Here is a previous thread on another site discussing something very similar, with a suggested alternative, which boils down to this: 是另一个站点上的上一个主题,讨论的内容非常相似,并带有建议的替代方法,其归结为:

You need to replace the NUL s before feeding them into the QTextStream , as it will not pass them through. 您需要先将NUL替换为QTextStream ,然后再将它们通过。 The suggestion there is to use a QDataStream . 建议使用QDataStream Maybe you don't need a TextStream or any Stream at all, and could just read the files into memory as binary and replace the NUL s with your choice of substitute before writing out again. 也许您根本不需要TextStream或任何Stream ,并且可以将文件作为二进制文件读取到内存中,并在再次写入之前用您选择的替代项替换NUL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM