[Qt-interest] Write struct in a QByteArray or QFile
Oliver.Knoll at comit.ch
Oliver.Knoll at comit.ch
Mon Jun 8 16:35:28 CEST 2009
Tiago Correia wrote on Monday, June 08, 2009 2:44 PM:
> Hi,
>
> I'm trying to write my own struct to a file. I'm trying to use QFile,
> but I'm getting the correct data.
> ...
> f.write( (char*) &wh, sizeof( WAVEHEADER ) );
>
> Any ideias?
It is not very obvious from the docs http://doc.qtsoftware.com/4.5/qiodevice.html#write, but I think write() writes an 8-bit *string* (characters) to the file, that is it terminates when it encounters a NUL (\0) character (or when it has written 'maxSize' characters, whatever comes first). Actually the Qt docs only mention the *string* here: http://doc.qtsoftware.com/4.5/qiodevice.html#write-2, a method which was only introduced in Qt 4.5:
"Writes data from a zero-terminated string of 8-bit characters to the device."
But I think this comment also applies to http://doc.qtsoftware.com/4.5/qiodevice.html#write.
Especially since there are methods in the API which specifically deal with *binary* data, such as:
http://doc.qtsoftware.com/4.5/qiodevice.html#writeData
or maybe the version which takes a QByteArray as argument:
http://doc.qtsoftware.com/4.5/qiodevice.html#write-3 (but not sure whether that also stops writing when it encounters NUL!).
You could also try something like this:
QFile file("/some/path/data.bin");
if (file.open(QIODevice::WriteOnly) == true) {
QDataStream dataStream(&file);
int nofBytesWritten = dataStream.writeRawData(static_cast<const char *>(&wh), sizeof(WAVEHEADER));
...
} ...
Alternatively with the http://doc.qtsoftware.com/4.5/qdatastream.html#writeBytes flavour...
Cheers, Oliver
--
Oliver Knoll
Dipl. Informatik-Ing. ETH
COMIT AG - ++41 79 520 95 22
More information about the Qt-interest-old
mailing list