QDir Class▲
-
Header: QDir
-
CMake:
find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
-
qmake: QT += core
-
Group: QDir is part of Input/Output and Networking, Implicitly Shared Classes
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:/Documents and Settings"
)
On Windows, the second example above will be translated to C:\Documents and Settings 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.
Paths starting with a colon (:) are always considered absolute, as they denote a QResource.
Navigation and Directory Operations▲
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:
Return Value |
||
---|---|---|
current() |
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 &
lt;&
lt; " Bytes Filename"
&
lt;&
lt; std::
endl;
for
(int
i =
0
; i &
lt; list.size(); ++
i) {
QFileInfo fileInfo =
list.at(i);
std::
cout &
lt;&
lt; qPrintable(QString("%1 %2"
).arg(fileInfo.size(), 10
)
.arg(fileInfo.fileName()));
std::
cout &
lt;&
lt; std::
endl;
}
return
0
;
}
See Also▲
Member Type Documentation▲
enum QDir::Filter▲
flags QDir::Filters
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:
Constant |
Value |
Description |
---|---|---|
QDir::Dirs |
0x001 |
List directories that match the filters. |
QDir::AllDirs |
0x400 |
List all directories; i.e. don't apply the filters to directory names. |
QDir::Files |
0x002 |
List files. |
QDir::Drives |
0x004 |
List disk drives (ignored under Unix). |
QDir::NoSymLinks |
0x008 |
Do not list symbolic links (ignored by operating systems that don't support symbolic links). |
QDir::NoDotAndDotDot |
NoDot | NoDotDot |
Do not list the special entries "." and "..". |
QDir::NoDot |
0x2000 |
Do not list the special entry ".". |
QDir::NoDotDot |
0x4000 |
Do not list the special entry "..". |
QDir::AllEntries |
Dirs | Files | Drives |
List directories, files, drives and symlinks (this does not list broken symlinks unless you specify System). |
QDir::Readable |
0x010 |
List files for which the application has read access. The Readable value needs to be combined with Dirs or Files. |
QDir::Writable |
0x020 |
List files for which the application has write access. The Writable value needs to be combined with Dirs or Files. |
QDir::Executable |
0x040 |
List files for which the application has execute access. The Executable value needs to be combined with Dirs or Files. |
QDir::Modified |
0x080 |
Only list files that have been modified (ignored on Unix). |
QDir::Hidden |
0x100 |
List hidden files (on Unix, files starting with a "."). |
QDir::System |
0x200 |
List system files (on Unix, FIFOs, sockets and device files are included; on Windows, .lnk files are included) |
QDir::CaseSensitive |
0x800 |
The 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 permissons for a directory, use the entryInfoList() function to get the associated QFileInfo objects and then use the QFileInfo::permissons() to obtain the permissions and ownership for each file.
The Filters type is a typedef for QFlags<Filter>. It stores an OR combination of Filter values.
enum QDir::SortFlag▲
flags QDir::SortFlags
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:
Constant |
Value |
Description |
---|---|---|
QDir::Name |
0x00 |
Sort by name. |
QDir::Time |
0x01 |
Sort by time (modification time). |
QDir::Size |
0x02 |
Sort by file size. |
QDir::Type |
0x80 |
Sort by file type (extension). |
QDir::Unsorted |
0x03 |
Do not sort. |
QDir::NoSort |
-1 |
Not sorted by default. |
QDir::DirsFirst |
0x04 |
Put the directories first, then the files. |
QDir::DirsLast |
0x20 |
Put the files first, then the directories. |
QDir::Reversed |
0x08 |
Reverse the sort order. |
QDir::IgnoreCase |
0x10 |
Sort case-insensitively. |
QDir::LocaleAware |
0x40 |
Sort 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.
The SortFlags type is a typedef for QFlags<SortFlag>. It stores an OR combination of SortFlag values.
Member Function Documentation▲
QDir::QDir(const QString &path = QString())▲
Constructs a QDir pointing to the given directory path. If path is empty the program's working directory, ("."), is used.
See Also▲
See also currentPath()
QDir::QDir(const QString &path, const QString &nameFilter, QDir::SortFlags sort = SortFlags(Name | IgnoreCase), QDir::Filters filters = AllEntries)▲
Constructs a QDir with path path, that filters its entries by name using nameFilter and by attributes using filters. It also sorts the names using sort.
The default nameFilter is an empty string, which excludes nothing; the default filters is AllEntries, which also excludes nothing. The default sort is Name | IgnoreCase, i.e. sort by name case-insensitively.
If path is an empty string, QDir uses "." (the current directory). If nameFilter is an empty string, QDir uses the name filter "*" (all files).
path need not exist.
See Also▲
See also exists(), setPath(), setNameFilters(), setFilter(), setSorting()
[since 6.0] QDir::QDir(const std::filesystem::path &path)▲
Constructs a QDir pointing to the given directory path. If path is empty the program's working directory, ("."), is used.
This function was introduced in Qt 6.0.
See Also▲
See also currentPath()
[since 6.0] QDir::QDir(const std::filesystem::path &path, const QString &nameFilter, QDir::SortFlags sort = SortFlags(Name | IgnoreCase), QDir::Filters filters = AllEntries)▲
Constructs a QDir with path path, that filters its entries by name using nameFilter and by attributes using filters. It also sorts the names using sort.
The default nameFilter is an empty string, which excludes nothing; the default filters is AllEntries, which also excludes nothing. The default sort is Name | IgnoreCase, i.e. sort by name case-insensitively.
If path is empty, QDir uses "." (the current directory). If nameFilter is an empty string, QDir uses the name filter "*" (all files).
path need not exist.
This function was introduced in Qt 6.0.
See Also▲
See also exists(), setPath(), setNameFilters(), setFilter(), setSorting()
QDir::QDir(const QDir &dir)▲
Constructs a QDir object that is a copy of the QDir object for directory dir.
See Also▲
See also operator=()
QDir::~QDir()▲
Destroys the QDir object frees up its resources. This has no effect on the underlying directory in the file system.
QString QDir::absoluteFilePath(const QString &fileName) const▲
Returns the absolute path name of a file in the directory. Does not check if the file actually exists in the directory; but see exists(). Redundant multiple separators or "." and ".." directories in fileName are not removed (see cleanPath()).
See Also▲
See also relativeFilePath(), filePath(), canonicalPath()
QString QDir::absolutePath() const▲
Returns the absolute path (a path that starts with "/" or with a drive specification), which may contain symbolic links, but never contains redundant ".", ".." or multiple separators.
See Also▲
See also setPath(), canonicalPath(), exists(), cleanPath(), dirName(), absoluteFilePath()
[static] void QDir::addSearchPath(const QString &prefix, const QString &path)▲
[static, since 6.0] void QDir::addSearchPath(const QString &prefix, const std::filesystem::path &path)▲
This is an overloaded function.
This function was introduced in Qt 6.0.
QString QDir::canonicalPath() const▲
Returns the canonical path, i.e. a path without symbolic links or redundant "." or ".." elements.
On systems that do not have symbolic links this function will always return the same string that absolutePath() returns. If the canonical path does not exist (normally due to dangling symbolic links) canonicalPath() returns an empty string.
Example:
QString bin =
"/local/bin"
; // where /local/bin is a symlink to /usr/bin
QDir binDir(bin);
QString canonicalBin =
binDir.canonicalPath();
// canonicalBin now equals "/usr/bin"
QString ls =
"/local/bin/ls"
; // where ls is the executable "ls"
QDir lsDir(ls);
QString canonicalLs =
lsDir.canonicalPath();
// canonicalLS now equals "/usr/bin/ls".
See Also▲
See also path(), absolutePath(), exists(), cleanPath(), dirName(), absoluteFilePath()
bool QDir::cd(const QString &dirName)▲
Changes the QDir's directory to dirName.
Returns true if the new directory exists; otherwise returns false. Note that the logical cd() operation is not performed if the new directory does not exist.
Calling cd("..") is equivalent to calling cdUp().
See Also▲
See also cdUp(), isReadable(), exists(), path()
bool QDir::cdUp()▲
Changes directory by moving one directory up from the QDir's current directory.
Returns true if the new directory exists; otherwise returns false. Note that the logical cdUp() operation is not performed if the new directory does not exist.
See Also▲
See also cd(), isReadable(), exists(), path()
[static] QString QDir::cleanPath(const QString &path)▲
Returns path with directory separators normalized (that is, platform-native separators converted to "/") and redundant ones removed, and "."s and ".."s resolved (as far as possible).
Symbolic links are kept. This function does not return the canonical path, but rather the simplest version of the input. For example, "./local" becomes "local", "local/../bin" becomes "bin" and "/local/usr/../bin" becomes "/local/bin".
See Also▲
See also absolutePath(), canonicalPath()
uint QDir::count() const▲
Returns the total number of directories and files in the directory.
Equivalent to entryList().count().
See Also▲
See also operator[](), entryList()
[static] QDir QDir::current()▲
Returns the application's current directory.
The directory is constructed using the absolute path of the current directory, ensuring that its path() will be the same as its absolutePath().
See Also▲
See also currentPath(), setCurrent(), home(), root(), temp()
[static] QString QDir::currentPath()▲
Returns the absolute path of the application's current directory. The current directory is the last directory set with QDir::setCurrent() or, if that was never called, the directory at which this application was started at by the parent process.
See Also▲
See also current(), setCurrent(), homePath(), rootPath(), tempPath(), QCoreApplication::applicationDirPath()
QString QDir::dirName() const▲
Returns the name of the directory; this is not the same as the path, e.g. a directory with the name "mail", might have the path "/var/spool/mail". If the directory has no name (e.g. it is the root directory) an empty string is returned.
No check is made to ensure that a directory with this name actually exists; but see exists().
See Also▲
See also path(), filePath(), absolutePath(), absoluteFilePath()
[static] QFileInfoList QDir::drives()▲
Returns a list of the root directories on this system.
On Windows this returns a list of QFileInfo objects containing "C:/", "D:/", etc. On other operating systems, it returns a list containing just one root directory (i.e. "/").
See Also▲
QFileInfoList QDir::entryInfoList(const QStringList &nameFilters, QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const▲
Returns a list of QFileInfo objects for all the files and directories in the directory, ordered according to the name and attribute filters previously set with setNameFilters() and setFilter(), and sorted according to the flags set with setSorting().
The name filter, file attribute filter, and sorting specification can be overridden using the nameFilters, filters, and sort arguments.
Returns an empty list if the directory is unreadable, does not exist, or if nothing matches the specification.
See Also▲
See also entryList(), setNameFilters(), setSorting(), setFilter(), isReadable(), exists()
QFileInfoList QDir::entryInfoList(QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const▲
This is an overloaded function.
Returns a list of QFileInfo objects for all the files and directories in the directory, ordered according to the name and attribute filters previously set with setNameFilters() and setFilter(), and sorted according to the flags set with setSorting().
The attribute filter and sorting specifications can be overridden using the filters and sort arguments.
Returns an empty list if the directory is unreadable, does not exist, or if nothing matches the specification.
See Also▲
See also entryList(), setNameFilters(), setSorting(), setFilter(), isReadable(), exists()
QStringList QDir::entryList(const QStringList &nameFilters, QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const▲
Returns a list of the names of all the files and directories in the directory, ordered according to the name and attribute filters previously set with setNameFilters() and setFilter(), and sorted according to the flags set with setSorting().
The name filter, file attribute filter, and sorting specification can be overridden using the nameFilters, filters, and sort arguments.
Returns an empty list if the directory is unreadable, does not exist, or if nothing matches the specification.
See Also▲
See also entryInfoList(), setNameFilters(), setSorting(), setFilter()
QStringList QDir::entryList(QDir::Filters filters = NoFilter, QDir::SortFlags sort = NoSort) const▲
This is an overloaded function.
Returns a list of the names of all the files and directories in the directory, ordered according to the name and attribute filters previously set with setNameFilters() and setFilter(), and sorted according to the flags set with setSorting().
The attribute filter and sorting specifications can be overridden using the filters and sort arguments.
Returns an empty list if the directory is unreadable, does not exist, or if nothing matches the specification.
To list symlinks that point to non existing files, System must be passed to the filter.
See Also▲
See also entryInfoList(), setNameFilters(), setSorting(), setFilter()
bool QDir::exists(const QString &name) const▲
Returns true if the file called name exists; otherwise returns false.
Unless name contains an absolute file path, the file name is assumed to be relative to the directory itself, so this function is typically used to check for the presence of files within a directory.
See Also▲
See also QFileInfo::exists(), QFile::exists()
bool QDir::exists() const▲
This is an overloaded function.
Returns true if the directory exists; otherwise returns false. (If a file with the same name is found this function will return false).
The overload of this function that accepts an argument is used to test for the presence of files and directories within a directory.
See Also▲
See also QFileInfo::exists(), QFile::exists()
QString QDir::filePath(const QString &fileName) const▲
Returns the path name of a file in the directory. Does not check if the file actually exists in the directory; but see exists(). If the QDir is relative the returned path name will also be relative. Redundant multiple separators or "." and ".." directories in fileName are not removed (see cleanPath()).
See Also▲
See also dirName(), absoluteFilePath(), isRelative(), canonicalPath()
[since 6.0] std::filesystem::path QDir::filesystemAbsolutePath() const▲
Returns absolutePath() as std::filesystem::path.
This function was introduced in Qt 6.0.
See Also▲
See also absolutePath()
[since 6.0] std::filesystem::path QDir::filesystemCanonicalPath() const▲
Returns canonicalPath() as std::filesystem::path.
This function was introduced in Qt 6.0.
See Also▲
See also canonicalPath()
[since 6.0] std::filesystem::path QDir::filesystemPath() const▲
Returns path() as std::filesystem::path.
This function was introduced in Qt 6.0.
See Also▲
See also path()
QDir::Filters QDir::filter() const▲
[static] QString QDir::fromNativeSeparators(const QString &pathName)▲
Returns pathName using '/' as file separator. On Windows, for instance, fromNativeSeparators("c:\\winnt\\system32") returns "c:/winnt/system32".
The returned string may be the same as the argument on some operating systems, for example on Unix.
See Also▲
See also toNativeSeparators(), separator()
[static] QDir QDir::home()▲
Returns the user's home directory.
The directory is constructed using the absolute path of the home directory, ensuring that its path() will be the same as its absolutePath().
See homePath() for details.
See Also▲
[static] QString QDir::homePath()▲
Returns the absolute path of the user's home directory.
Under Windows this function will return the directory of the current user's profile. Typically, this is:
C
:/
Documents and
Settings/
Username
Use the toNativeSeparators() function to convert the separators to the ones that are appropriate for the underlying operating system.
If the directory of the current user's profile does not exist or cannot be retrieved, the following alternatives will be checked (in the given order) until an existing and available path is found:
-
The path specified by the USERPROFILE environment variable.
-
The path formed by concatenating the HOMEDRIVE and HOMEPATH environment variables.
-
The path specified by the HOME environment variable.
-
The path returned by the rootPath() function (which uses the SystemDrive environment variable)
-
The C:/ directory.
Under non-Windows operating systems the HOME environment variable is used if it exists, otherwise the path returned by the rootPath().
See Also▲
See also home(), currentPath(), rootPath(), tempPath()
bool QDir::isAbsolute() const▲
Returns true if the directory's path is absolute; otherwise returns false. See isAbsolutePath().
Paths starting with a colon (:) are always considered absolute, as they denote a QResource.
See Also▲
See also isRelative(), makeAbsolute(), cleanPath()
[static] bool QDir::isAbsolutePath(const QString &path)▲
Returns true if path is absolute; returns false if it is relative.
Paths starting with a colon (:) are always considered absolute, as they denote a QResource.
See Also▲
See also isAbsolute(), isRelativePath(), makeAbsolute(), cleanPath(), QResource
[since 5.9] bool QDir::isEmpty(QDir::Filters filters = Filters(AllEntries | NoDotAndDotDot)) const▲
Returns whether the directory is empty.
Equivalent to count() == 0 with filters QDir::AllEntries | QDir::NoDotAndDotDot, but faster as it just checks whether the directory contains at least one entry.
Unless you set the filters flags to include QDir::NoDotAndDotDot (as the default value does), no directory is empty.
This function was introduced in Qt 5.9.
See Also▲
bool QDir::isReadable() const▲
Returns true if the directory is readable and we can open files by name; otherwise returns false.
A false value from this function is not a guarantee that files in the directory are not accessible.
See Also▲
See also QFileInfo::isReadable()
bool QDir::isRelative() const▲
Returns true if the directory path is relative; otherwise returns false. (Under Unix a path is relative if it does not start with a "/").
Paths starting with a colon (:) are always considered absolute, as they denote a QResource.
See Also▲
See also makeAbsolute(), isAbsolute(), isAbsolutePath(), cleanPath()
[static] bool QDir::isRelativePath(const QString &path)▲
Returns true if path is relative; returns false if it is absolute.
Paths starting with a colon (:) are always considered absolute, as they denote a QResource.
See Also▲
See also isRelative(), isAbsolutePath(), makeAbsolute()
bool QDir::isRoot() const▲
Returns true if the directory is the root directory; otherwise returns false.
If the directory is a symbolic link to the root directory this function returns false. If you want to test for this use canonicalPath(), e.g.
QDir dir("/tmp/root_link"
);
dir =
dir.canonicalPath();
if
(dir.isRoot())
qWarning("It is a root link"
);
See Also▲
[static constexpr, since 5.6] QChar QDir::listSeparator()▲
Returns the native path list separator: ':' under Unix and ';' under Windows.
This function was introduced in Qt 5.6.
See Also▲
See also separator()
bool QDir::makeAbsolute()▲
Converts the directory path to an absolute path. If it is already absolute nothing happens. Returns true if the conversion succeeded; otherwise returns false.
See Also▲
See also isAbsolute(), isAbsolutePath(), isRelative(),