0

我的问题是变量内容总是空的。这是我的代码:

QFile file("/home/qt/Client/file.txt");
if(file.open(QIODevice::ReadOnly)){
    qDebug("File opened");
}

QDataStream fileData(&file);

QByteArray content;
QDataStream out(&content, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_7);  

out << static_cast<quint16>(0) << "file" << "/home/qt/Client/file.txt" << fileData;

out.device()->seek(0);
out << static_cast<quint16>(content.size());

qDebug() << content.constData();

tcpSocket->write(content);

输出 :

File opened

内容始终为空

感谢您的帮助

4

1 回答 1

4

content不为空,但如果将其解释为 C 风格的以 0 结尾的字符串,它将显示为空。

当你写:

out.device()->seek(0);
out << static_cast<quint16>(content.size());

这会将 to 的前两个字节设置为content大端content.size()格式(这是默认设置)。因此,如果content.size()小于 255,则 的第一个字节content.constData()将为 0 ( '\0')。任何使用需要 C 样式字符串的函数进行打印的尝试constData()都不会输出任何内容,因为您的“字符串”以“字符串结尾”标记开头。

如果你想查看完整的内容content,你应该单独打印它的所有字符并使用类似的东西hexdump来查看原始数据。

如果我这样做而不是这样做,这就是我得到的qDebug() << content.constData();

for (int i=0; i<content.size(); i++) {
    std::cout << content.constData()[i];
}

运行时的输出(文件仅包含 20 个'a'字符):

 $ ./qt | hexdump -C
00000000  00 40 00 00 00 05 66 69  6c 65 00 00 00 00 19 2f  |.@....file...../|
00000010  68 6f 6d 65 2f 71 74 2f  43 6c 69 65 6e 74 2f 66  |home/qt/Client/f|
00000020  69 6c 65 2e 74 78 74 00  00 00 00 14 61 61 61 61  |ile.txt.....aaaa|
00000030  61 61 61 61 61 61 61 61  61 61 61 61 61 61 61 61  |aaaaaaaaaaaaaaaa|
00000040

如果我使用过:

std::cout << content.constData();

由于第一个 0 字符,将没有输出。

如果您的数据较长,并且大小content大于 255,则第一个字符将不再为 0,但您将打印两个垃圾字符,因为 Qt 通过首先编写它来序列化 QString(和大多数其他类型)长度(此处为 32 位),然后是其内容。由于它采用大端表示法,因此第一个字节很有可能为 0。

注释输出:

00000000  00 40 00 00 00 05 66 69  6c 65 00 00 00 00 19 2f  |.@....file...../|
          <u16> < str len > <  str data   > < str len > <
00000010  68 6f 6d 65 2f 71 74 2f  43 6c 69 65 6e 74 2f 66  |home/qt/Client/f|
                               str data...
00000020  69 6c 65 2e 74 78 74 00  00 00 00 14 61 61 61 61  |ile.txt.....aaaa|
            str data            >  <data len > < 
00000030  61 61 61 61 61 61 61 61  61 61 61 61 61 61 61 61  |aaaaaaaaaaaaaaaa|
                    data                                 >
于 2011-10-05T07:36:57.187 回答