[Qt-interest] how to write data into file

Thiago Macieira thiago at kde.org
Tue Oct 11 15:50:26 CEST 2011


On Tuesday, 11 de October de 2011 08:35:57 Vincent Cai wrote:
> Dear all,
> 
>          I try to write some different type of data into a file, but failed.
> From below code, what I hope to get in file is: 01 00 02 00 00 00 03 But
> what I exactly get is: 123
>          Could anybody tell me how to modify below code?
> 
>     QFile TSAFile;
>     QString tmp;
>     const QChar *data;
>     quint8 a = 0x01;
>     quint16 b = 0x02;
>     quint32 c = 0x03;
>     tmp += QString::number(a, 16);
>     tmp += QString::number(b, 16);
>     tmp += QString::number(c, 16);
>     data = tmp.constData();
>     while (!data->isNull())
>     {
>         TSAFile.write((char*)data);
>         ++data;
>     }
>     TSAFile.setFileName("C:\\QtDebug.bin");
>     TSAFile.close();

Replace all instances of QString with QByteArray and of QChar with char. 
Remove all casts too (the only one). And don't use QString::number or 
QByteArray::number -- those will convert a 0x01 to "1".

Note that QChar is 2 bytes long, so your code above, casting to char, will 
have unpredictable behaviour. Sometimes it will write 1 byte, sometimes 2 or 
more.

Also note that the output you told us doesn't correspond to the code you 
pasted. You didn't even open the file in the code above!

If you want to write a binary 8-bit value, why don't you write exactly that?

	TSAFile.write(reinterpret_cast<char *>(&a), sizeof a);

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel Open Source Technology Center
      PGP/GPG: 0x6EF45358; fingerprint:
      E067 918B B660 DBD1 105C  966C 33F5 F005 6EF4 5358
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 190 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20111011/94398336/attachment.bin 


More information about the Qt-interest-old mailing list