How to read a binary file in bytes with Qt?
In Qt, you can use the QFile class to read binary files byte by byte. Below is an example code:
QFile file("binaryfile.bin");
if (file.open(QIODevice::ReadOnly)) {
QByteArray data = file.readAll();
file.close();
int byteCount = data.size();
// 对读取的二进制数据进行处理
qDebug() << "读取的字节数:" << byteCount;
} else {
qDebug() << "无法打开文件";
}
The code above first creates a QFile object and opens the binary file named “binaryfile.bin” in read-only mode using the open() function. Then, the readAll() function is used to read the contents of the file into a QByteArray object all at once. Finally, the size() function can be used to get the number of bytes read.
Please note that the above code assumes that the contents of the binary file can fit entirely into memory. If the file is large, it may be necessary to read it in batches to avoid a memory overflow.