QDir Class

The QDir class provides access to directory structures and their contents. More...

Header: #include <QDir>
qmake: QT += core

Note: All functions in this class are reentrant.

Public Types

enum Filter { Dirs, AllDirs, Files, Drives, NoSymLinks, …, CaseSensitive }
enum SortFlag { Name, Time, Size, Type, Unsorted, …, LocaleAware }

Macros

void Q_CLEANUP_RESOURCE(name)
void Q_INIT_RESOURCE(name)

Detailed Description

A QDir is used to manipulate path names, access information regarding paths and files, and manipulate the underlying file system. It can also be used to access Qt's resource system.

Qt uses "/" as a universal directory separator in the same way that "/" is used as a path separator in URLs. If you always use "/" as a directory separator, Qt will translate your paths to conform to the underlying operating system.

A QDir can point to a file using either a relative or an absolute path. Absolute paths begin with the directory separator (optionally preceded by a drive specification under Windows). Relative file names begin with a directory name or a file name and specify a path relative to the current directory.

Examples of absolute paths:

 QDir("/home/user/Documents")
 QDir("C:/Users")

On Windows, the second example above will be translated to C:\Users when used to access files.

Examples of relative paths:

 QDir("images/landscape.png")

You can use the isRelative() or isAbsolute() functions to check if a QDir is using a relative or an absolute file path. Call makeAbsolute() to convert a relative QDir to an absolute one.

Note: Paths starting with a colon (:) are always considered absolute, as they denote a QResource.

A directory's path can be obtained with the path() function, and a new path set with the setPath() function. The absolute path to a directory is found by calling absolutePath().

The name of a directory is found using the dirName() function. This typically returns the last element in the absolute path that specifies the location of the directory. However, it can also return "." if the QDir represents the current directory.

 QDir("Documents/Letters/Applications").dirName() // "Applications"
 QDir().dirName()                                 // "."

The path for a directory can also be changed with the cd() and cdUp() functions, both of which operate like familiar shell commands. When cd() is called with the name of an existing directory, the QDir object changes directory so that it represents that directory instead. The cdUp() function changes the directory of the QDir object so that it refers to its parent directory; i.e. cd("..") is equivalent to cdUp().

Directories can be created with mkdir(), renamed with rename(), and removed with rmdir().

You can test for the presence of a directory with a given name by using exists(), and the properties of a directory can be tested with isReadable(), isAbsolute(), isRelative(), and isRoot().

The refresh() function re-reads the directory's data from disk.

Files and Directory Contents

Directories contain a number of entries, representing files, directories, and symbolic links. The number of entries in a directory is returned by count(). A string list of the names of all the entries in a directory can be obtained with entryList(). If you need information about each entry, use entryInfoList() to obtain a list of QFileInfo objects.

Paths to files and directories within a directory can be constructed using filePath() and absoluteFilePath(). The filePath() function returns a path to the specified file or directory relative to the path of the QDir object; absoluteFilePath() returns an absolute path to the specified file or directory. Neither of these functions checks for the existence of files or directory; they only construct paths.

 QDir directory("Documents/Letters");
 QString path = directory.filePath("contents.txt");
 QString absolutePath = directory.absoluteFilePath("contents.txt");

Files can be removed by using the remove() function. Directories cannot be removed in the same way as files; use rmdir() to remove them instead.

It is possible to reduce the number of entries returned by entryList() and entryInfoList() by applying filters to a QDir object. You can apply a name filter to specify a pattern with wildcards that file names need to match, an attribute filter that selects properties of entries and can distinguish between files and directories, and a sort order.

Name filters are lists of strings that are passed to setNameFilters(). Attribute filters consist of a bitwise OR combination of Filters, and these are specified when calling setFilter(). The sort order is specified using setSorting() with a bitwise OR combination of SortFlags.

You can test to see if a filename matches a filter using the match() function.

Filter and sort order flags may also be specified when calling entryList() and entryInfoList() in order to override previously defined behavior.

The Current Directory and Other Special Paths

Access to some common directories is provided with a number of static functions that return QDir objects. There are also corresponding functions for these that return strings:

QDirQStringReturn Value
current()currentPath()The application's working directory
home()homePath()The user's home directory
root()rootPath()The root directory
temp()tempPath()The system's temporary directory

The setCurrent() static function can also be used to set the application's working directory.

If you want to find the directory containing the application's executable, see QCoreApplication::applicationDirPath().

The drives() static function provides a list of root directories for each device that contains a filing system. On Unix systems this returns a list containing a single root directory "/"; on Windows the list will usually contain C:/, and possibly other drive letters such as D:/, depending on the configuration of the user's system.

Path Manipulation and Strings

Paths containing "." elements that reference the current directory at that point in the path, ".." elements that reference the parent directory, and symbolic links can be reduced to a canonical form using the canonicalPath() function.

Paths can also be simplified by using cleanPath() to remove redundant "/" and ".." elements.

It is sometimes necessary to be able to show a path in the native representation for the user's platform. The static toNativeSeparators() function returns a copy of the specified path in which each directory separator is replaced by the appropriate separator for the underlying operating system.

Examples

Check if a directory exists:

 QDir dir("example");
 if (!dir.exists())
     qWarning("Cannot find the example directory");

(We could also use the static convenience function QFile::exists().)

Traversing directories and reading a file:

 QDir dir = QDir::root();                 // "/"
 if (!dir.cd("tmp")) {                    // "/tmp"
     qWarning("Cannot find the \"/tmp\" directory");
 } else {
     QFile file(dir.filePath("ex1.txt")); // "/tmp/ex1.txt"
     if (!file.open(QIODevice::ReadWrite))
         qWarning("Cannot create the file %s", file.name());
 }

A program that lists all the files in the current directory (excluding symbolic links), sorted by size, smallest first:

 #include <QDir>
 #include <iostream>

 int main(int argc, char *argv[])
 {
     QCoreApplication app(argc, argv);
     QDir dir;
     dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
     dir.setSorting(QDir::Size | QDir::Reversed);

     QFileInfoList list = dir.entryInfoList();
     std::cout << "     Bytes Filename" << std::endl;
     for (int i = 0; i < list.size(); ++i) {
         QFileInfo fileInfo = list.at(i);
         std::cout << qPrintable(QString("%1 %2").arg(fileInfo.size(), 10)
                                                 .arg(fileInfo.fileName()));
         std::cout << std::endl;
     }
     return 0;
 }

See also QFileInfo, QFile, QFileDialog, QCoreApplication::applicationDirPath(), and Find Files Example.

Member Type Documentation

enum QDir::Filter

This enum describes the filtering options available to QDir; e.g. for entryList() and entryInfoList(). The filter value is specified by combining values from the following list using the bitwise OR operator:

ConstantValueDescription
QDir::Dirs0x001List directories that match the filters.
QDir::AllDirs0x400List all directories; i.e. don't apply the filters to directory names.
QDir::Files0x002List files.
QDir::Drives0x004List disk drives (ignored under Unix).
QDir::NoSymLinks0x008Do not list symbolic links (ignored by operating systems that don't support symbolic links).
QDir::NoDotAndDotDotNoDot | NoDotDotDo not list the special entries "." and "..".
QDir::NoDot0x2000Do not list the special entry ".".
QDir::NoDotDot0x4000Do not list the special entry "..".
QDir::AllEntriesDirs | Files | DrivesList directories, files, drives and symlinks (this does not list broken symlinks unless you specify System).
QDir::Readable0x010List files for which the application has read access. The Readable value needs to be combined with Dirs or Files.
QDir::Writable0x020List files for which the application has write access. The Writable value needs to be combined with Dirs or Files.
QDir::Executable0x040List files for which the application has execute access. The Executable value needs to be combined with Dirs or Files.
QDir::Modified0x080Only list files that have been modified (ignored on Unix).
QDir::Hidden0x100List hidden files (on Unix, files starting with a ".").
QDir::System0x200List system files (on Unix, FIFOs, sockets and device files are included; on Windows, .lnk files are included)
QDir::CaseSensitive0x800The filter should be case sensitive.

Functions that use Filter enum values to filter lists of files and directories will include symbolic links to files and directories unless you set the NoSymLinks value.

A default constructed QDir will not filter out files based on their permissions, so entryList() and entryInfoList() will return all files that are readable, writable, executable, or any combination of the three. This makes the default easy to write, and at the same time useful.

For example, setting the Readable, Writable, and Files flags allows all files to be listed for which the application has read access, write access or both. If the Dirs and Drives flags are also included in this combination then all drives, directories, all files that the application can read, write, or execute, and symlinks to such files/directories can be listed.

To retrieve the permissions for a directory, use the entryInfoList() function to get the associated QFileInfo objects and then use the QFileInfo::permissions() to obtain the permissions and ownership for each file.

enum QDir::SortFlag

This enum describes the sort options available to QDir, e.g. for entryList() and entryInfoList(). The sort value is specified by OR-ing together values from the following list:

ConstantValueDescription
QDir::Name0x00Sort by name.
QDir::Time0x01Sort by time (modification time).
QDir::Size0x02Sort by file size.
QDir::Type0x80Sort by file type (extension).
QDir::Unsorted0x03Do not sort.
QDir::NoSort-1Not sorted by default.
QDir::DirsFirst0x04Put the directories first, then the files.
QDir::DirsLast0x20Put the files first, then the directories.
QDir::Reversed0x08Reverse the sort order.
QDir::IgnoreCase0x10Sort case-insensitively.
QDir::LocaleAware0x40Sort items appropriately using the current locale settings.

You can only specify one of the first four.

If you specify both DirsFirst and Reversed, directories are still put first, but in reverse order; the files will be listed after the directories, again in reverse order.

Macro Documentation

void Q_CLEANUP_RESOURCE(name)

Unloads the resources specified by the .qrc file with the base name name.

Normally, Qt resources are unloaded automatically when the application terminates, but if the resources are located in a plugin that is being unloaded, call Q_CLEANUP_RESOURCE() to force removal of your resources.

Note: This macro cannot be used in a namespace. Please see the Q_INIT_RESOURCE documentation for a workaround.

Example:

 Q_CLEANUP_RESOURCE(myapp);

This function was introduced in Qt 4.1.

See also Q_INIT_RESOURCE() and The Qt Resource System.

void Q_INIT_RESOURCE(name)

Initializes the resources specified by the .qrc file with the specified base name. Normally, when resources are built as part of the application, the resources are loaded automatically at startup. The Q_INIT_RESOURCE() macro is necessary on some platforms for resources stored in a static library.

For example, if your application's resources are listed in a file called myapp.qrc, you can ensure that the resources are initialized at startup by adding this line to your main() function:

 Q_INIT_RESOURCE(myapp);

If the file name contains characters that cannot be part of a valid C++ function name (such as '-'), they have to be replaced by the underscore character ('_').

Note: This macro cannot be used in a namespace. It should be called from main(). If that is not possible, the following workaround can be used to init the resource myapp from the function MyNamespace::myFunction:

 inline void initMyResource() { Q_INIT_RESOURCE(myapp); }

 namespace MyNamespace
 {
     ...

     void myFunction()
     {
         initMyResource();
     }
 }

See also Q_CLEANUP_RESOURCE() and The Qt Resource System.