简体   繁体   中英

Qt - Reading file containing multiple NULL characters

I have gotten a file, which contains multiple NULL charactes /0 in a line. My goal was to load the file and replace the /0 with something else, but I experience some problems doing that.

Qt stops reading the file, after it get's to the point, where the NULL character appears.

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.

Read the file with as 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.

Update (comments, look at underscore_d 's answer):

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.

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. The suggestion there is to use a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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