Home > Articles > Programming > C/C++

C++ GUI Programming with Qt4: Input/Output

This chapter covers reading and writing binary data and text, traversing directories, embedding resources, and inter-process communication.
This chapter is from the book

12. Input/Output

  • Reading and Writing Binary Data
  • Reading and Writing Text
  • Traversing Directories
  • Embedding Resources
  • Inter-Process Communication

The need to read from or write to files or other devices is common to almost every application. Qt provides excellent support for I/O through QIODevice, a powerful abstraction that encapsulates "devices" capable of reading and writing blocks of bytes. Qt includes the following QIODevice subclasses:

QFile

Accesses files in the local file system and in embedded resources

QTemporaryFile

Creates and accesses temporary files in the local file system

QBuffer

Reads data from or writes data to a QByteArray

QProcess

Runs external programs and handles inter-process communication

QTcpSocket

Transfers a stream of data over the network using TCP

QUdpSocket

Sends or receives UDP datagrams over the network

QSslSocket

Transfers an encrypted data stream over the network using SSL/TLS

QProcess, QTcpSocket, QUdpSocket, and QSslSocket are sequential devices, meaning that the data can be accessed only once, starting from the first byte and progressing serially to the last byte. QFile, QTemporaryFile, and QBuffer are random-access devices, so bytes can be read any number of times from any position; they provide the QIODevice::seek() function for repositioning the file pointer.

In addition to the device classes, Qt also provides two higher-level stream classes that we can use to read from, and write to, any I/O device: QDataStream for binary data and QTextStream for text. These classes take care of issues such as byte ordering and text encodings, ensuring that Qt applications running on different platforms or in different countries can read and write each other's files. This makes Qt's I/O classes much more convenient than the corresponding Standard C++ classes, which leave these issues to the application programmer.

QFile makes it easy to access individual files, whether they are in the file system or embedded in the application's executable as resources. For applications that need to identify whole sets of files to work on, Qt provides the QDir and QFileInfo classes, which handle directories and provide information about the files inside them.

The QProcess class allows us to launch external programs and to communicate with them through their standard input, standard output, and standard error channels (cin, cout, and cerr). We can set the environment variables and working directory that the external application will use. By default, communication with the process is asynchronous (non-blocking), but it is also possible to block on certain operations.

Networking and reading and writing XML are such substantial topics that we cover separately in their own dedicated chapters (Chapter 15 and Chapter 16).

Reading and Writing Binary Data

The simplest way to load and save binary data with Qt is to instantiate a QFile, to open the file, and to access it through a QDataStream object. QDataStream provides a platform-independent storage format that supports basic C++ types such as int and double, and many Qt data types, including QByteArray, QFont, QImage, QPixmap, QString, and QVariant, as well as Qt container classes such as QList<T> and QMap<K, T>.

Here's how we would store an integer, a QImage, and a QMap<QString, QColor> in a file called facts.dat:

QImage image("philip.png");

QMap<QString, QColor> map;
map.insert("red", Qt::red);
map.insert("green", Qt::green);
map.insert("blue", Qt::blue);

QFile file("facts.dat");
if (!file.open(QIODevice::WriteOnly)) {
    std::cerr << "Cannot open file for writing: "
              << qPrintable(file.errorString()) << std::endl;
    return;
}

QDataStream out(&file);
out.setVersion(QDataStream::Qt_4_3);

out << quint32(0x12345678) << image << map;

If we cannot open the file, we inform the user and return. The qPrintable() macro returns a const char * for a QString. (Another approach would have been to use QString::toStdString(), which returns a std::string, for which <iostream> has a << overload.)

If the file is opened successfully, we create a QDataStream and set its version number. The version number is an integer that influences the way Qt data types are represented (basic C++ data types are always represented the same way). In Qt 4.3, the most comprehensive format is version 9. We can either hard-code the constant 9 or use the QDataStream::Qt_4_3 symbolic name.

To ensure that the number 0x12345678 is written as an unsigned 32-bit integer on all platforms, we cast it to quint32, a data type that is guaranteed to be exactly 32 bits. To ensure interoperability, QDataStream standardizes on big-endian by default; this can be changed by calling setByteOrder().

We don't need to explicitly close the file, since this is done automatically when the QFile variable goes out of scope. If we want to verify that the data has actually been written, we can call flush() and check its return value (true on success).

The code to read back the data mirrors the code we used to write it:

quint32 n;
QImage image;
QMap<QString, QColor> map;

QFile file("facts.dat");
if (!file.open(QIODevice::ReadOnly)) {
    std::cerr << "Cannot open file for reading: "
              << qPrintable(file.errorString()) << std::endl;
    return;
}

QDataStream in(&file);
in.setVersion(QDataStream::Qt_4_3);

in >> n >> image >> map;

The QDataStream version we use for reading is the same as the one we used for writing. This must always be the case. By hard-coding the version number, we guarantee that the application can always read and write the data (assuming it is compiled with Qt 4.3 or any later Qt version).

QDataStream stores data in such a way that we can read it back seamlessly. For example, a QByteArray is represented as a 32-bit byte count followed by the bytes themselves. QDataStream can also be used to read and write raw bytes, without any byte count header, using readRawBytes() and writeRawBytes().

Error handling when reading from a QDataStream is fairly easy. The stream has a status() value that can be QDataStream::Ok, QDataStream::ReadPastEnd, or QDataStream::ReadCorruptData. Once an error has occurred, the >> operator always reads zero or empty values. This means that we can often simply read an entire file without worrying about potential errors and check the status() value at the end to see if what we read was valid.

QDataStream handles a variety of C++ and Qt data types; the complete list is available at http://doc.trolltech.com/4.3/datastreamformat.html. We can also add support for our own custom types by overloading the << and >> operators. Here's the definition of a custom data type that can be used with QDataStream:

class Painting
{
public:
    Painting() { myYear = 0; }
    Painting(const QString &title, const QString &artist, int year) {
        myTitle = title;
        myArtist = artist;
        myYear = year;
    }

    void setTitle(const QString &title) { myTitle = title; }
    QString title() const { return myTitle; }
    ...

private:
    QString myTitle;
    QString myArtist;
    int myYear;
};

QDataStream &operator<<(QDataStream &out, const Painting &painting);
QDataStream &operator>>(QDataStream &in, Painting &painting);

Here's how we would implement the << operator:

QDataStream &operator<<(QDataStream &out, const Painting &painting)
{
    out << painting.title() << painting.artist()
        << quint32(painting.year());
    return out;
}

To output a Painting, we simply output two QStrings and a quint32. At the end of the function, we return the stream. This is a common C++ idiom that allows us to use a chain of << operators with an output stream. For example:

out << painting1 << painting2 << painting3;

The implementation of operator>>() is similar to that of operator<<():

QDataStream &operator>>(QDataStream &in, Painting &painting)
{
    QString title;
    QString artist;
    quint32 year;

    in >> title >> artist >> year;
    painting = Painting(title, artist, year);
    return in;
}

There are several benefits to providing streaming operators for custom data types. One of them is that it allows us to stream containers that use the custom type. For example:

QList<Painting> paintings = ...;
out << paintings;

We can read in containers just as easily:

QList<Painting> paintings;
in >> paintings;

This would result in a compiler error if Painting didn't support << or >>. Another benefit of providing streaming operators for custom types is that we can store values of these types as QVariants, which makes them more widely usable—for example, by QSettings. This works provided that we register the type using qRegisterMetaTypeStreamOperators<T>() beforehand, as explained in Chapter 11 (p. 292).

When we use QDataStream, Qt takes care of reading and writing each type, including containers with an arbitrary number of items. This relieves us from the need to structure what we write and from performing any kind of parsing on what we read. Our only obligation is to ensure that we read all the types in exactly the same order as we wrote them, leaving Qt to handle all the details.

QDataStream is useful both for our own custom application file formats and for standard binary formats. We can read and write standard binary formats using the streaming operators on basic types (such as quint16 or float) or using readRawBytes() and writeRawBytes(). If the QDataStream is being used purely to read and write basic C++ data types, we don't even need to call setVersion().

So far, we loaded and saved data with the stream's version hard-coded as QDataStream::Qt_4_3. This approach is simple and safe, but it does have one small drawback: We cannot take advantage of new or updated formats. For example, if a later version of Qt added a new attribute to QFont (in addition to its point size, family, etc.) and we hard-coded the version number to Qt_4_3, that attribute wouldn't be saved or loaded. There are two solutions. The first approach is to embed the QDataStream version number in the file:

QDataStream out(&file);
out << quint32(MagicNumber) << quint16(out.version());

(MagicNumber is a constant that uniquely identifies the file type.) This approach ensures that we always write the data using the most recent version of QDataStream, whatever that happens to be. When we come to read the file, we read the stream version:

quint32 magic;
quint16 streamVersion;

QDataStream in(&file);
in >> magic >> streamVersion;

if (magic != MagicNumber) {
    std::cerr << "File is not recognized by this application"
              << std::endl;
} else if (streamVersion > in.version()) {
    std::cerr << "File is from a more recent version of the "
              << "application" << std::endl;
    return false;
}

in.setVersion(streamVersion);

We can read the data as long as the stream version is less than or equal to the version used by the application; otherwise, we report an error.

If the file format contains a version number of its own, we can use it to deduce the stream version number instead of storing it explicitly. For example, let's suppose that the file format is for version 1.3 of our application. We might then write the data as follows:

QDataStream out(&file);
out.setVersion(QDataStream::Qt_4_3);
out << quint32(MagicNumber) << quint16(0x0103);

When we read it back, we determine which QDataStream version to use based on the application's version number:

QDataStream in(&file);
in >> magic >> appVersion;

if (magic != MagicNumber) {
    std::cerr << "File is not recognized by this application"
              << std::endl;
    return false;
} else if (appVersion > 0x0103) {
    std::cerr << "File is from a more recent version of the "
              << "application" << std::endl;
    return false;
}

if (appVersion < 0x0103) {
    in.setVersion(QDataStream::Qt_3_0);
} else {
    in.setVersion(QDataStream::Qt_4_3);
}

In this example, we specify that any file saved with versions prior to 1.3 of the application uses data stream version 4 (Qt_3_0), and that files saved with version 1.3 of the application use data stream version 9 (Qt_4_3).

In summary, there are three policies for handling QDataStream versions: hard-coding the version number, explicitly writing and reading the version number, and using different hard-coded version numbers depending on the application's version. Any of these policies can be used to ensure that data written by an old version of an application can be read by a new version, even if the new version links against a more recent version of Qt. Once we have chosen a policy for handling QDataStream versions, reading and writing binary data using Qt is both simple and reliable.

If we want to read or write a file in one go, we can avoid using QDataStream and instead use QIODevice's write() and readAll() functions. For example:

bool copyFile(const QString &source, const QString &dest)
{
    QFile sourceFile(source);
    if (!sourceFile.open(QIODevice::ReadOnly))
        return false;

    QFile destFile(dest);
    if (!destFile.open(QIODevice::WriteOnly))
        return false;

    destFile.write(sourceFile.readAll());

    return sourceFile.error() == QFile::NoError
           && destFile.error() == QFile::NoError;
}

In the line where readAll() is called, the entire contents of the input file are read into a QByteArray, which is then passed to the write() function to be written to the output file. Having all the data in a QByteArray requires more memory than reading item by item, but it offers some advantages. For example, we can then use qCompress() and qUncompress() to compress and uncompress the data. A less memory-hungry alternative to using qCompress() and qUncompress() is QtIOCompressor from Qt Solutions. A QtIOCompressor compresses the stream it writes and decompresses the stream it reads, without storing the entire file in memory.

There are other scenarios in which accessing QIODevice directly is more appropriate than using QDataStream. QIODevice provides a peek() function that returns the next data bytes without moving the device position as well as an ungetChar() function that "unreads" a byte. This works both for random-access devices (such as files) and for sequential devices (such as network sockets). There is also a seek() function that sets the device position, for devices that support random access.

Binary file formats provide the most versatile and most compact means of storing data, and QDataStream makes accessing binary data easy. In addition to the examples in this section, we already saw the use of QDataStream in Chapter 4 to read and write Spreadsheet files, and we will see it again in Chapter 21, where we use it to read and write Windows cursor files.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020