I need to receive binary data(reading float) through a QTcpSocket and write them into Qfile using QDatastream. But I am having some problems with QDataStream. As follows, I can only achieve it using this way :
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 have to create two Qdatastream and write float into Qfile after reading it.I mean, can I read stream and write it into file directly by one Qdatastream in order to getting more efficient.
Am I having some blind spot about the usage of QDataStream?Anyone can help me to solved my problem?Many thanks.
QDataStream
is designed to provide platform independent data serialization.
For example, you want to save some float to a file (or to send it over tcp stream) in some binary format. Then this float should be read from that file (or received from tcp) on another PC with different CPU and even different byte order (endianness).
So, QDataStream
can be used for such task. It allows you to encode C++ basic datatypes and to decode the original values on any other platform.
If you just want to save binary data from a TCP stream as is to a binary file then you do not need QDataStream
.
You can do it directly either synchronously blocking thread or asynchronously using readyRead() socket signal.
Example 1. Blocking socket for non-GUI thread
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);
}
}
Those examples are based on the documentation of QAbstractSocket Class (there you can find detailed explanation how it works).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With