FilePath Class
class Utils::FilePathThe FilePath class is an abstraction for handles to objects in a (possibly remote) file system, similar to a URL or, in the local case, a path to a file or directory. More...
Header: | #include <FilePath> |
Public Functions
QString | baseName() const |
Utils::FilePath | canonicalPath() const |
Qt::CaseSensitivity | caseSensitivity() const |
Utils::FilePath | cleanPath() const |
void | clear() |
QString | completeBaseName() const |
QString | completeSuffix() const |
bool | contains(const QString &s) const |
bool | endsWith(const QString &s) const |
bool | exists() const |
bool | isChildOf(const Utils::FilePath &s) const |
bool | isEmpty() const |
bool | isNewerThan(const QDateTime &timeStamp) const |
bool | isRelativePath() const |
bool | isWritableDir() const |
bool | isWritableFile() const |
void | iterateDirectory(const Utils::FilePath::IterateDirCallback &callBack, const Utils::FileFilter &filter) const |
QString | nativePath() const |
Utils::FilePath | onDevice(const Utils::FilePath &deviceTemplate) const |
Utils::FilePath | parentDir() const |
QChar | pathComponentSeparator() const |
QChar | pathListSeparator() const |
std::optional<FilePath> | refersToExecutableFile(Utils::FilePath::MatchScope matchScope) const |
Utils::FilePath | relativeChildPath(const Utils::FilePath &parent) const |
Utils::FilePath | relativePathFrom(const Utils::FilePath &anchor) const |
bool | removeRecursively(QString *error = nullptr) const |
Utils::FilePath | resolvePath(const Utils::FilePath &tail) const |
Utils::FilePath | resolvePath(const QString &tail) const |
Utils::FilePath | resolveSymlinks() const |
Utils::FilePath | searchInDirectories(const Utils::FilePaths &dirs, const Utils::FilePath::PathFilter &filter = {}) const |
QString | shortNativePath() const |
bool | startsWith(const QString &s) const |
bool | startsWithDriveLetter() const |
QStringView | suffixView() const |
Utils::FilePath | symLinkTarget() const |
QString | toFSPathString() const |
QFileInfo | toFileInfo() const |
QString | toString() const |
QString | toUserOutput() const |
Utils::FilePath | withNewPath(const QString &newPath) const |
QString | withTildeHomePath() const |
Static Public Members
QString | calcRelativePath(const QString &absolutePath, const QString &absoluteAnchorPath) |
Utils::FilePath | fromFileInfo(const QFileInfo &info) |
Utils::FilePath | fromString(const QString &filepath) |
Utils::FilePath | fromStringWithExtension(const QString &filepath, const QString &defaultExtension) |
Utils::FilePath | fromUserInput(const QString &filePath) |
Utils::FilePath | fromUtf8(const char *filename, int filenameSize = -1) |
Detailed Description
Ideally, all of Qt Creator code should use FilePath for this purpose, but for historic reasons there are still large parts using QString.
FilePaths are internally stored as triple of strings, with one part ("scheme") identifying an access method, a second part ("host") a file system (e.g. a host) and a third part ("path") identifying a (potential) object on the systems.
FilePath follows the Unix paradigm of "everything is a file": There is no conceptional difference between FilePaths referring to plain files or directories.
A FilePath is implicitly associated with an operating system via its host part. The path part of a FilePath is internally stored with forward slashes, independent of the associated OS.
The path parts of FilePaths associated with Windows (and macOS, unless selected otherwise in the settings) are compared case-insensitively to each other. Note that comparisons for equivalence generally need out-of-band knowledge, as there may be multiple FilePath representations for the same file (e.g. different access methods may lead to the same file).
There are several conversions between FilePath and other string-like representations:
- FilePath::fromUserInput()
Convert string-like data from sources originating outside of Qt Creator, e.g. from human input in GUI controls, from environment variables and from command-line parameters to Qt Creator.
The input can contain both slashes and backslashes and will be parsed and normalized.
- FilePath::nativePath()
Converts the FilePath to the slash convention of the associated OS and drops the scheme and host parts.
This is useful to interact with the facilities of the associated OS, e.g. when passing this FilePath as an argument to a command executed on the associated OS.
Note: The FilePath passed as executable to a CommandLine is typically not touched by user code. QtcProcess will use it to determine the remote system and apply the necessary conversions internally.
- FilePath::toFSPathString()
Converts the FilePath to a [drive:]/__qtc_devices__/scheme/host/path string.
The result works in most cases also with remote setups and QDir/QFileInfo but is slower than direct FilePath use and should only be used when proper porting to FilePath is too difficult, or not possible, e.g. when external Qt based libraries are used that do not use FilePath.
- FilePath::toUserOutput()
Converts the FilePath to the slash convention of the associated OS and retains the scheme and host parts.
This is rarely useful for remote paths as there is practically no consumer of this style.
- FilePath::displayName()
Converts the FilePath to the slash convention of the associated OS and adds the scheme and host as a " on <device>" suffix.
This is useful for static user-facing output in he GUI
- FilePath::fromVariant(), FilePath::toVariant()
These are used to interface QVariant-based API, e.g. settings or item model (internal) data.
- FilePath::fromString(), FilePath::toString()
These are used for internal interfaces to code areas that still use QString based file paths for simple storage and retrieval.
In most cases, use of one of the more specialized above is more appropriate.
Conversion of string-like data should always happen at the outer boundary of Qt Creator code, using fromUserInput()
for in-bound communication, and depending on the medium nativePath()
or displayName()
for out-bound communication.
Communication with QVariant based Qt API should use fromVariant()
and toVariant()
.
Uses of fromString()
and toString()
should be phased out by transforming code from QString based file path to FilePath. An exception here are fragments of paths of a FilePath that are later used with pathAppended()
or similar which should be kept as QString.
UNC paths will retain their "//" begin, and are recognizable by this.
Member Function Documentation
QString FilePath::baseName() const
\returns
the base name of the file without the path.
The base name consists of all characters in the file up to (but not including) the first '.' character.
[static]
QString FilePath::calcRelativePath(const QString &absolutePath, const QString &absoluteAnchorPath)
\returns
the relativePath of absolutePath to given absoluteAnchorPath. Both paths must be an absolute path to a directory. Example usage:
qDebug() << FilePath::calcRelativePath("/foo/b/ar", "/foo/c");
The debug output will be "../b/ar".
See also FilePath::relativePath.
Utils::FilePath FilePath::canonicalPath() const
*
Recursively resolves possibly present symlinks in this file name. * On Windows, also resolves SUBST and re-mounted NTFS drives. * Unlike QFileInfo::canonicalFilePath(), this function will not return an empty * string if path doesn't exist. * * \returns
the canonical path.
Qt::CaseSensitivity FilePath::caseSensitivity() const
Returns the caseSensitivity of the path.
\returns
The caseSensitivity of the path. This is currently only based on the Host OS. For device paths, Qt::CaseSensitive
is always returned.
Utils::FilePath FilePath::cleanPath() const
Cleans path part similar to QDir::cleanPath()
- 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".
void FilePath::clear()
Clears all parts of the FilePath.
QString FilePath::completeBaseName() const
\returns
the complete base name of the file without the path.
The complete base name consists of all characters in the file up to (but not including) the last '.' character. In case of ".ui.qml" it will be treated as one suffix.
QString FilePath::completeSuffix() const
\returns
the complete suffix (extension) of the file.
The complete suffix consists of all characters in the file after (but not including) the first '.'.
bool FilePath::contains(const QString &s) const
\returns
whether path()
contains s.
bool FilePath::endsWith(const QString &s) const
\returns
whether path()
ends with s.
bool FilePath::exists() const
\returns
a bool indicating whether a file or directory with this FilePath exists.
[static]
Utils::FilePath FilePath::fromFileInfo(const QFileInfo &info)
Constructs a FilePath from info
[static]
Utils::FilePath FilePath::fromString(const QString &filepath)
Constructs a FilePath from filepath
filepath is not checked for validity. It can be given in the following forms:
- /some/absolute/local/path
- some/relative/path
- scheme://host/absolute/path
- scheme://host/./relative/path
Note: the ./ is verbatim part of the path
Some decoding happens when parsing the filepath A sequence %25 present in the host part is replaced by % in the host name, a sequence %2f present in the host part is replaced by / in the host name.
The path part might consist of several parts separated by /, independent of the platform or file system.
To create FilePath objects from strings possibly containing backslashes as path separator, use fromUserInput
.
See also toString and fromUserInput.
[static]
Utils::FilePath FilePath::fromStringWithExtension(const QString &filepath, const QString &defaultExtension)
Constructs a FilePath from filePath. The defaultExtension is appended to filePath if that does not have an extension already.
filePath is not checked for validity.
[static]
Utils::FilePath FilePath::fromUserInput(const QString &filePath)
Constructs a FilePath from filePath
The path filePath is cleaned and ~ replaces by the home path.
[static]
Utils::FilePath FilePath::fromUtf8(const char *filename, int filenameSize = -1)
Constructs a FilePath from filePath, which is encoded as UTF-8.
filePath is not checked for validity.
bool FilePath::isChildOf(const Utils::FilePath &s) const
\returns
whether FilePath is a child of s
bool FilePath::isEmpty() const
Checks if the path() is empty.
\returns
true if the path() is empty. The Host and Scheme of the part are ignored.
bool FilePath::isNewerThan(const QDateTime &timeStamp) const
Checks if this is newer than \p
timeStamp
timeStamp The time stamp to compare with \returns
true if this is newer than \p
timeStamp. If this is a directory, the function will recursively check all files and return true if one of them is newer than timeStamp. If this is a single file, true will be returned if the file is newer than timeStamp.
Returns whether at least one file in filePath has a newer date than \p
timeStamp.
bool FilePath::isRelativePath() const
Checks whether the path is relative
\returns
true if the path is relative.
bool FilePath::isWritableDir() const
\returns
a bool indicating whether this is a writable directory.
bool FilePath::isWritableFile() const
\returns
a bool indicating whether this is a writable file.
void FilePath::iterateDirectory(const Utils::FilePath::IterateDirCallback &callBack, const Utils::FileFilter &filter) const
This runs callBack on each directory entry matching all filters and either of the specified nameFilters. An empty nameFilters list matches every name.
QString FilePath::nativePath() const
\returns
a QString to pass to target system native commands, without the device prefix.
Converts the separators to the native format of the system this path belongs to.
Utils::FilePath FilePath::onDevice(const Utils::FilePath &deviceTemplate) const
Returns a path corresponding to the current object on the
same device as deviceTemplate. The FilePath needs to be local.
Example usage:
localDir = FilePath("/tmp/workingdir"); executable = FilePath::fromUrl("docker://123/bin/ls") realDir = localDir.onDevice(executable) assert(realDir == FilePath::fromUrl("docker://123/tmp/workingdir"))
deviceTemplate A path from which the host and scheme is taken.
\returns
A path on the same device as deviceTemplate.
Utils::FilePath FilePath::parentDir() const
Find the parent directory of a given directory.
Returns an empty FilePath if the current directory is already a root level directory.
\returns
FilePath with the last segment removed.
QChar FilePath::pathComponentSeparator() const
Returns the separator of path components for this path.
\returns
The path separator of the path.
QChar FilePath::pathListSeparator() const
Returns the path list separator for the device this path belongs to.
\returns
The path list separator of the device for this path
std::optional<FilePath> FilePath::refersToExecutableFile(Utils::FilePath::MatchScope matchScope) const
\returns
a bool indicating on whether a process with this FilePath's .nativePath() is likely to start.
This is equivalent to isExecutableFile()
in general. On Windows, it will check appending various suffixes, too.
Utils::FilePath FilePath::relativeChildPath(const Utils::FilePath &parent) const
Relative path from parent to this.
Returns a empty FilePath if this is not a child of \p
parent. That is, this never returns a path starting with "../" parent The Parent to calculate the relative path to. \returns
The relative path of this to \p
parent if this is a child of \p
parent.
Utils::FilePath FilePath::relativePathFrom(const Utils::FilePath &anchor) const
\returns
the relativePath of FilePath from a given anchor. Both, FilePath and anchor may be files or directories. Example usage:
FilePath filePath("/foo/b/ar/file.txt"); FilePath relativePath = filePath.relativePath("/foo/c"); qDebug() << relativePath
The debug output will be "../b/ar/file.txt".
bool FilePath::removeRecursively(QString *error = nullptr) const
Removes the directory this filePath refers too and its subdirectories recursively.
Note: The error parameter is optional.
\returns
A bool indicating whether the operation succeeded.
Utils::FilePath FilePath::resolvePath(const Utils::FilePath &tail) const
Appends the tail to this, if the tail is a relative path.
tail The tail to append. \returns
Returns tail if tail is absolute, otherwise this + tail.
Utils::FilePath FilePath::resolvePath(const QString &tail) const
Appends the tail to this, if the tail is a relative path.
tail The tail to append. \returns
Returns tail if tail is absolute, otherwise this + tail.
Utils::FilePath FilePath::resolveSymlinks() const
Recursively resolves symlinks if this is a symlink.
To resolve symlinks anywhere in the path, see canonicalPath. Unlike QFileInfo::canonicalFilePath(), this function will still return the expected deepest target file even if the symlink is dangling.
Note: Maximum recursion depth == 16.
\returns
the symlink target file path.
Utils::FilePath FilePath::searchInDirectories(const Utils::FilePaths &dirs, const Utils::FilePath::PathFilter &filter = {}) const
Search for a binary corresponding to this object in the PATH of the device implied by this object's scheme and host.
Example usage:
binary = FilePath::fromUrl("docker://123/./make); fullPath = binary.searchInDirectories(binary.deviceEnvironment().path()); assert(fullPath == FilePath::fromUrl("docker://123/usr/bin/make"))
QString FilePath::shortNativePath() const
Converts the path to a possibly shortened path with native separators.
Like QDir::toNativeSeparators(), but use prefix '~' instead of $HOME on unix systems when an absolute path is given.
\returns
the possibly shortened path with native separators.
bool FilePath::startsWith(const QString &s) const
\returns
whether path()
starts with s.
bool FilePath::startsWithDriveLetter() const
Checks whether the FilePath starts with a drive letter.
Defaults to false
if it is a non-Windows host or represents a path on device \returns
whether FilePath starts with a drive letter
QStringView FilePath::suffixView() const
\returns
the suffix (extension) of the file.
The suffix consists of all characters in the file after (but not including) the last '.'. In case of ".ui.qml" it will be treated as one suffix.
Utils::FilePath FilePath::symLinkTarget() const
\returns
an empty FilePath if this is not a symbolic linl
QString FilePath::toFSPathString() const
\returns
a QString for passing on to QString based APIs
This uses a /__qtc_devices__/host/path setup.
This works in most cases also with remote setups and QDir/QFileInfo etc. but is slower than direct FilePath use and should only be used when proper porting to FilePath is too difficult, or not possible, e.g. when external Qt based libraries are used that do not use FilePath.
See also fromUserInput().
QFileInfo FilePath::toFileInfo() const
\returns
a QFileInfo
QString FilePath::toString() const
\returns
a QString for passing through QString based APIs
Note: This is obsolete API and should be replaced by extended use of proper FilePath
, or, in case this is not possible by toFSPathString()
.
This uses a scheme://host/path setup and is, together with fromString, used to pass FilePath through QString
using code paths.
The result is not useful for use with cQDir and QFileInfo
and gets destroyed by some operations like QFileInfo::canonicalFile
.
See also toFSPathString().
QString FilePath::toUserOutput() const
returns a QString to display to the user, including the device prefix
Converts the separators to the native format of the system this path belongs to.
Utils::FilePath FilePath::withNewPath(const QString &newPath) const
Returns a FilePath with local path newPath on the same device as the current object.
Example usage:
devicePath = FilePath("docker://123/tmp"); newPath = devicePath.withNewPath("/bin/ls"); assert(realDir == FilePath::fromUrl("docker://123/bin/ls"))
QString FilePath::withTildeHomePath() const
On Linux/Mac replace user's home path with ~ in the toString()
result for this path after cleaning.
If path is not sub of home path, or when running on Windows, returns the input
© 2023 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.