How to perform file IO using QDataStream in Qt
This code snippet demonstrates how to use QDataStream for performing file read and write in Qt.
Article Metadata
Tested with
Devices(s): Emulator
Compatibility
Platform(s): Qt
Platform Security
Signing Required: Self-Signed
Capabilities: None
Article
Keywords: QDataStream
Created: james1980
(27 Jan 2009)
Last edited: hamishwillee
(11 Oct 2012)
Various Functions
- Sets the serialization byte order to bo.
in.setByteOrder(QDataStream::LittleEndian);
- Sets the version number of the data serialization format to v
QDataStream out(file); out.setVersion(QDataStream::Qt_4_0);
Source File
More About QDataStream: http://pepper.troll.no/s60prereleases/doc/qdatastream.html
#include "fileIO.h"
#include <QFile>
#include <QLabel>
#include <QDataStream>
fileIO::fileIO(QWidget *parent)
: QWidget(parent)
{
QFile file("c://test.txt");
file.open(QIODevice::WriteOnly);
QDataStream out(&file); // we will serialize the data into the file
out << "welcome to the Qt World"; // serialize a string
file.close();
QFile read("c://test.txt");
read.open(QIODevice::ReadOnly);
QDataStream in(&read); // read the data serialized from the file
QString str;
in >> str;
}
fileIO::~fileIO()
{
}


Contents
Dor666 - Memory leak
Hi,
I've tried this code like this in boost::test:
And it gives me memory leaks:
Detected memory leaks!
dor666 16:39, 20 November 2012 (EET)
Hamishwillee - Fixed up text
Hi Dor666
Firstly, thanks for posting this feedback. I've tidied your layout - you can use Help:Code Syntax Highlighting for marking up code -see Help:Formatting for other wiki markup. To edit the text look for "Admin" link next to the "Comment" title.
I suspect the problem is that QFile read is opened but never closed. Can you try replacing
with
Regards
Hamishhamishwillee 05:45, 21 November 2012 (EET)
Dor666 -
Hi Hammish. Thank you for quick reply and layout fix.
I think, that file is closed automatically in QFile destructor.
I've tried also this:
dor666 09:12, 21 November 2012 (EET)
Hamishwillee - I think you are probably right!
I have heard similar things before, but I can't find a reference sorry.hamishwillee 07:40, 22 November 2012 (EET)