Leo
Leo

Reputation: 43

Size of QByteArray is hard to compute?

Recently I programmed to do file transmission with Qt. Thought it worked now, I'm still curious about what happened. Please help me find out the reason. Many thanks.

Why the size of head is bigger than the sum of sizeof(qin32), sizeof(qint32) and length of file name?(I guess it is the reason of function - setVersion())

QFileInfo info(file_to_send.fileName());
QByteArray head;
QDataStream out(&head, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_0);
out << qint32(file_to_send.size() + info.fileName().length() + sizeof(qint32)*2)
    << qint32(info.fileName().length())
    << info.fileName();
tcpClient.write(head);

Upvotes: 1

Views: 884

Answers (2)

Marek R
Marek R

Reputation: 38092

You have made it to complicated. Pattern is like that:

QFileInfo info(file_to_send.fileName());
QByteArray head;
QDataStream out(&head, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_0);
out << qint32(0)
    << info.fileName(); // << YouCanAddMoreStuffHere;

out.device()->seek(0);
out << qint32(out.length());

tcpClient.write(head);

and read code:

void SomeClass::slotReadClient() { // slot connected to readyRead signal of QTcpSocket
    QTcpSocket *tcpSocket = (QTcpSocket*)sender();
    QDataStream clientReadStream(tcpSocket);

    while(true) {
        if (!next_block_size) {
            if (tcpSocket->bytesAvailable() < sizeof(qint32)) { // are size data available
                break;
            }
            clientReadStream >> next_block_size;
        }

        if (tcpSocket->bytesAvailable() < next_block_size) {
            break;
        }
        QString fileName;
        clientReadStream >> fileName; // >> YouCanAddMoreStuffHere; // same as above

        next_block_size = 0;
    }
}

Upvotes: 1

ratchet freak
ratchet freak

Reputation: 48216

info.filename() writes out its own length

if you don't want that then you can do

QFileInfo info(file_to_send.fileName());
QByteArray head;
QDataStream out(&head, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_0);
QByteArray filename = info.fileName().toLatin1();
out << qint32(file_to_send.size() + filename .length() + sizeof(qint32)*2);
    << qint32(filename .length())
out.writeRawData(fileName.constData(), filename.length());
tcpClient.write(head);

using writeRawData which bypasses any built in encoding

Upvotes: 0

Related Questions