O'Reilly logo

Programming with Qt, 2nd Edition by Matthias Kalle Dalheimer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 11. Working with Files and Directories

Few programs don’t deal with files and directories in some way. Filesystem manipulation is another inherently platform-dependent area. If you don’t plan to make your application available on multiple platforms and you are absolutely sure that nobody will ever ask you to, you can use the native functions to access files and directories provided by your operating system or development environment. However, if you need or want to be portable, using the classes that Qt provides might be a better choice. Even if portability is not important for you, the Qt classes might be useful because they provide easy, type-safe access to this functionality.

The Qt API for accessing files and directories mainly consists of the classes QIODevice, QFile, QFileInfo, and QDir. Two classes, QDataStream and QTextStream, are used to write binary and text data to files. Finally, the class QSettings makes it easy to store and retrieve simple configuration-like data.

We explain how to use these classes by means of three examples: reading a text file, recursing over a directory tree, and outputting information about one file. Then we finish the chapter by showing how to use QSettings.

Reading a Text File

To read a text file, you create a QFile object, assign the filename to this object, and open it. You then create a QTextStream object that works with the QFile object and read the data by means of the normal C++ input operators or with QTextStream::readLine() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required