Using Qdatastream to read data from a socket and write to a file

I need to get binary data (read float) via QTcpSocket and write it to Qfile using QDatastream. But I have problems with QDataStream. Thus, I can only achieve this as follows:

QDataStream in(socket); in.setFloatingPointPrecision ( QDataStream::SinglePrecision); float data; in >> data; QFile file("file.dat"); file.open(QIODevice::WriteOnly); QDataStream out(&file); out << data; 

I need to create two Qdatastream and write a float in a Qfile after reading it. I mean, can I read the stream and write it to a file directly with one Qdatastream to improve efficiency.

Do I have a blind spot about using QDataStream? Can anyone help me solve my problem? Many thanks.

+4
source share
1 answer

QDataStream designed to provide platform-independent data serialization.

For example, you want to save some float to a file (or send it over the tcp stream) in some binary format. Then this float should be read from this file (or obtained from tcp) on another PC with a different processor and even with a different byte order (endianness).

So, QDataStream can be used for such a task. It allows you to encode basic C ++ data types and decode source values ​​on any other platform.

If you just want to save binary data from a TCP stream, as well as a binary file, you do not need QDataStream . You can do this directly or synchronously, blocking the stream, or asynchronously using the readyRead () socket signal.

Example 1. Blocking socket for a stream without a GUI

 QFile file("out.bin"); if (!file.open(QIODevice::WriteOnly)) return; char buffer[50]; forever { int numRead = socket.read(buffer, 50); // do whatever with array file.write(buffer, numRead); if (numRead == 0 && !socket.waitForReadyRead()) break; } 

Example 2. Asynchronous non-blocking socket

 // This slot is connected to QAbstractSocket::readyRead() void SocketClass::readyReadSlot() { while (!socket.atEnd()) { QByteArray data = socket.read(100); file.write(data); } } 

These examples are based on the QAbstractSocket Class documentation (there you can find a detailed explanation of how this works).

+1
source

All Articles