FilePath Class | Extending Qt Creator Manual
Description: The 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.

- Extending Qt Creator Manual
- QtCreator
- FilePath
- Extending Qt Creator Manual 13.0.1

# FilePath Class

class Utils::FilePath

The 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>

- List of all members, including inherited members

## Public Functions

QString | baseName() const
Utils::FilePath | canonicalPath() const
Qt::CaseSensitivity | caseSensitivity() const
Utils::FilePath | chopped(int n) const
Utils::FilePath | cleanPath() const
void | clear()
QString | completeBaseName() const
QString | completeSuffix() const
bool | contains(const QString &s) const
bool | createDir() const
QString | displayName(const QString &args = {}) const
bool | endsWith(const QString &s) const
Utils::expected_str<void> | ensureWritableDir() const
bool | exists() const
bool | isChildOf(const Utils::FilePath &s) const
bool | isEmpty() const
bool | isExecutableFile() 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 | parentDir() const
QChar | pathComponentSeparator() const
QChar | pathListSeparator() const
std::optional<Utils::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::FilePathPredicate &filter = {}, Utils::FilePath::MatchScope matchScope = WithAnySuffix) 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
QVariant | toVariant() const
Utils::FilePath | withNewMappedPath(const Utils::FilePath &newPath) const
Utils::FilePath | withNewPath(const QString &newPath) const
QString | withTildeHomePath() const

## Static Public Members

QString | calcRelativePath(QStringView absolutePath, QStringView absoluteAnchorPath)
Utils::FilePath | fromFileInfo(const QFileInfo &info)
Utils::FilePath | fromString(const QString &filepath)
Utils::FilePath | fromStringWithExtension(const QString &filepath, const QString &defaultExtension)
Utils::FilePath | fromUrl(const QUrl &url)
Utils::FilePath | fromUserInput(const QString &filePath)
Utils::FilePath | fromUtf8(const char *filename, int filenameSize = -1)
Utils::FilePath | fromVariant(const QVariant &variant)

## 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. The Process 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 the 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(QStringView absolutePath, QStringView absoluteAnchorPath)

Returns the relative path 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::isRelativePath(), FilePath::relativePathFrom(), and FilePath::relativeChildPath().

### 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.

This is currently only based on the Host OS. For device paths, `Qt::CaseSensitive` is always returned.

### Utils::FilePath FilePath::chopped(int n) const

Returns a path with the n characters of the local path removed. Example usage:

     backup = FilePath("/tmp/example.txt.backup");
     real = backup.chopped(7);
     assert(real == FilePath("/tmp/example.txt"))

### 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::createDir() const

Creates a directory in this location.

Returns true if the directory could be created, false if not, even if it existed before.

See also ensureWritableDir().

### QString FilePath::displayName(const QString &args = {}) const

Converts the file path 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 the GUI.

If args is not empty, it is added to the output after the file path: "<path> <args> on <device>".

### bool FilePath::endsWith(const QString &s) const

Returns whether `path()` ends with s.

### Utils::expected_str<void> FilePath::ensureWritableDir() const

Re-uses or creates a directory in this location.

Returns true if the directory is writable afterwards.

See also createDir().

### 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::fromUrl(const QUrl &url)

Constructs a FilePath from url.

See also toVariant().

### `[static]` Utils::FilePath FilePath::fromUserInput(const QString &filePath)

Constructs a FilePath from filePath

The path filePath is cleaned, and ~ is replaced by the home path.

### `[static]` Utils::FilePath FilePath::fromUtf8(const char *filename, int filenameSize = -1)

Constructs a FilePath from filename with filenameSize, which is encoded as UTF-8.

filename is not checked for validity.

### `[static]` Utils::FilePath FilePath::fromVariant(const QVariant &variant)

Constructs a FilePath from variant.

See also toVariant().

### 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::isExecutableFile() const

Returns a bool indicating whether this is an executable file.

### bool FilePath::isNewerThan(const QDateTime &timeStamp) const

Checks if this is newer than timeStamp.

The time stamp timeStamp to compare with. Returns `true` if this is newer than 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 the file path has a newer date than 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

Runs callBack on each directory entry matching the filter.

### 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::parentDir() const

Finds the parent directory of the file path.

Returns an empty file path if the file path is already a root level directory.

Returns a file path 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<Utils::FilePath> FilePath::refersToExecutableFile(Utils::FilePath::MatchScope matchScope) const

Returns a bool indicating on whether a process with this FilePath's native path is likely to start.

This is equivalent to isExecutableFile() in general. On Windows, it might append various suffixes depending on matchScope.

### 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 parent. parent is the Parent to calculate the relative path to. That is, this never returns a path starting with "../"

Returns the relative path of this to parent if this is a child of parent.

### Utils::FilePath FilePath::relativePathFrom(const Utils::FilePath &anchor) const

Returns the relative path 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.relativePathFrom("/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.

Returns the tail if the 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.

Returns the tail if the 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::FilePathPredicate &filter = {}, Utils::FilePath::MatchScope matchScope = WithAnySuffix) const

Search for a binary corresponding to this object on each directory entry specified by dirs matching the filter with the matchScope of the file path.

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. 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 link.

### 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.

### QVariant FilePath::toVariant() const

Returns the FilePath as a variant.

To be used for type-agnostic internal interfaces like storage in QAbstractItemModels.

### Utils::FilePath FilePath::withNewMappedPath(const Utils::FilePath &newPath) const

Returns a path corresponding to newPath object on the same device as the current object.

This may involve device-specific translations like converting windows style paths to unix style paths with suitable file system case or handling of drive letters: C:/dev/src -> /c/dev/src

Example usage:

     localDir = FilePath("/tmp/workingdir");
     executable = FilePath::fromUrl("docker://123/bin/ls")
     realDir = executable.withNewMappedPath(localDir)
     assert(realDir == FilePath::fromUrl("docker://123/tmp/workingdir"))

### 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