2011-10-04 40 views
0

我的问题是变量内容总是空的。 这里是我的代码:通过QDataStream和QTcpSocket读取和发送文件

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

content不是空的,但如果你把它解释作为C风格的0结束字符串,它会出现为空。

当你写:

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

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

如果你想看到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 |[email protected]/| 
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 c,所以没有输出哈日。

如果你的数据是更长的时间,并且content大小比255越大,第一个字符将不再是0,但由于Qt的序列化的QString你会打印垃圾,别无其他的两个字符(最其他类型)首先写入其长度(32位在这里),然后它的内容。自大端符号,第一个字节的是0

注释输出非常高的机会:

00000000 00 40 00 00 00 05 66 69 6c 65 00 00 00 00 19 2f |[email protected]/| 
      <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         > 
+0

或者你可以“简单”输出“content.toPercentEncoding()”而不是“内容.constData()“来转义特殊字符,包括'\ 0'。 – alexisdm