Utils::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.h> |
Public Functions
| Utils::FilePath | absoluteFilePath() const |
| Utils::FilePath | absolutePath() const |
| Utils::FileStreamHandle | asyncCopy(const Utils::Continuation<> &cont, const Utils::FilePath &target) const |
| Utils::FileStreamHandle | asyncRead(const Utils::Continuation<QByteArray> &cont) const |
| Utils::FileStreamHandle | asyncWrite(const Utils::Continuation<qint64> &cont, const QByteArray &data) const |
| QString | baseName() const |
| qint64 | bytesAvailable() 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 |
| Utils::Result<> | copyFile(const Utils::FilePath &target) const |
| Utils::Result<> | copyRecursively(const Utils::FilePath &target) const |
| bool | createDir() const |
| Utils::Result<> | createSymLink(const Utils::FilePath &symLink) const |
| Utils::Result<Utils::FilePath> | createTempDir() const |
| Utils::Result<Utils::FilePath> | createTempFile() const |
| Utils::Environment | deviceEnvironment() const |
| Utils::Result<Utils::Environment> | deviceEnvironmentWithError() const |
| Utils::FilePaths | devicePathEnvironmentVariable() const |
| Utils::FilePaths | dirEntries(QDir::Filters filters) const |
| Utils::FilePaths | dirEntries(const Utils::FileFilter &filter, QDir::SortFlags sort = QDir::NoSort) const |
| QString | displayName(const QString &args = {}) const |
| bool | endsWith(const QString &s) const |
| bool | ensureExistingFile() const |
| Utils::Result<> | ensureReachable(const Utils::FilePath &other) const |
| Utils::Result<> | ensureWritableDir() const |
| bool | equalsCaseSensitive(const Utils::FilePath &other) const |
| bool | exists() const |
| Utils::Result<QByteArray> | fileContents(qint64 maxSize = -1, qint64 offset = 0) const |
| QString | fileName() const |
| QStringView | fileNameView() const |
| QString | fileNameWithPathComponents(int pathComponents) const |
| qint64 | fileSize() const |
| QString | group() const |
| uint | groupId() const |
| bool | hasHardLinks() const |
| QStringView | host() const |
| Utils::FilePath | intern() const |
| bool | isAbsolutePath() const |
| bool | isChildOf(const Utils::FilePath &s) const |
| bool | isEmpty() const |
| bool | isExecutableFile() const |
| bool | isLocal() const |
| bool | isNewerThan(const QDateTime &timeStamp) const |
| bool | isRelativePath() const |
| bool | isResourceFile() const |
| bool | isRootPath() const |
| bool | isSameDevice(const Utils::FilePath &other) const |
| bool | isSameExecutable(const Utils::FilePath &other) const |
| bool | isSameFile(const Utils::FilePath &other) const |
| bool | isWritableDir() const |
| bool | isWritableFile() const |
| void | iterateDirectory(const Utils::FilePath::IterateDirCallback &callBack, const Utils::FileFilter &filter) const |
| QDateTime | lastModified() const |
| Utils::Result<Utils::FilePath> | localSource() const |
| Utils::Result<> | makeWritable() const |
| QString | nativePath() const |
| Utils::OsType | osType() const |
| QString | owner() const |
| uint | ownerId() const |
| Utils::FilePath | parentDir() const |
| QString | path() const |
| Utils::FilePath | pathAppended(const QString &path) const |
| QChar | pathComponentSeparator() const |
| QList<QStringView> | pathComponents() const |
| QChar | pathListSeparator() const |
| QStringView | pathView() const |
| QFileDevice::Permissions | permissions() const |
| std::optional<Utils::FilePath> | prefixRemoved(const QString &str) const |
| Utils::TextEncoding | processStdErrEncoding() const |
| Utils::TextEncoding | processStdOutEncoding() const |
| std::optional<Utils::FilePath> | refersToExecutableFile(Utils::FilePath::MatchScope matchScope) const |
| Utils::FilePath | relativeChildPath(const Utils::FilePath &parent) const |
| QString | relativeNativePathFromDir(const Utils::FilePath &anchorDir) const |
| QString | relativePathFromDir(const Utils::FilePath &anchorDir) const |
| Utils::Result<> | removeFile() const |
| Utils::Result<> | removeRecursively() const |
| Utils::Result<> | renameFile(const Utils::FilePath &target) const |
| Utils::FilePath | resolvePath(const QString &tail) const |
| Utils::FilePath | resolvePath(const Utils::FilePath &tail) const |
| Utils::FilePath | resolveSymlinks() const |
| QStringView | scheme() const |
| Utils::FilePaths | searchAllInDirectories(const Utils::FilePaths &dirs, const Utils::FilePathPredicate &filter = {}, Utils::FilePath::MatchScope matchScope = WithAnySuffix) const |
| Utils::FilePaths | searchAllInPath() const |
| Utils::FilePaths | searchAllInPath(const Utils::FilePaths &additionalDirs, Utils::FilePath::PathAmending amending = AppendToPath, const Utils::FilePathPredicate &filter = {}, Utils::FilePath::MatchScope matchScope = WithAnySuffix) const |
| void | searchHereAndInParents(const std::function<IterationPolicy (const FilePath &)> &constraint) const |
| Utils::FilePath | searchHereAndInParents(const QString &fileName, QDir::Filter type) const |
| Utils::FilePath | searchHereAndInParents(const QStringList &fileNames, QDir::Filter type) const |
| Utils::FilePath | searchInDirectories(const Utils::FilePaths &dirs, const Utils::FilePathPredicate &filter = {}, Utils::FilePath::MatchScope matchScope = WithAnySuffix) const |
| Utils::FilePath | searchInPath() const |
| Utils::FilePath | searchInPath(const Utils::FilePaths &additionalDirs, Utils::FilePath::PathAmending amending = AppendToPath, const Utils::FilePathPredicate &filter = {}, Utils::FilePath::MatchScope matchScope = WithAnySuffix) const |
| void | setParts(const QStringView scheme, const QStringView host, const QStringView path) |
| Utils::Result<> | setPermissions(QFileDevice::Permissions permissions) const |
| QString | shortNativePath() const |
| bool | startsWith(const QString &s) const |
| bool | startsWithDriveLetter() const |
| Utils::FilePath | stringAppended(const QString &str) const |
| QString | suffix() const |
| QStringView | suffixView() const |
| Utils::FilePath | symLinkTarget() const |
| std::optional<Utils::FilePath> | tailRemoved(const QString &str) const |
| Utils::Result<Utils::FilePath> | tmpDir() const |
| QString | toFSPathString() const |
| QFileInfo | toFileInfo() const |
| QVariant | toSettings() const |
| QUrl | toUrl() const |
| QString | toUrlishString() const |
| QString | toUserOutput() const |
| QVariant | toVariant() const |
| Utils::FilePath | withExecutableSuffix() const |
| Utils::FilePath | withNewMappedPath(const Utils::FilePath &newPath) const |
| Utils::FilePath | withNewPath(const QString &newPath) const |
| Utils::FilePath | withSuffix(const QString &suffix) const |
| QString | withTildeHomePath() const |
| Utils::Result<qint64> | writeFileContents(const QByteArray &data) const |
| Utils::FilePath | operator/(const QString &str) const |
| Utils::FilePath & | operator/=(const QString &str) |
Static Public Members
| Utils::FilePath | currentWorkingPath() |
| Utils::FilePath | fromFileInfo(const QFileInfo &info) |
| Utils::FilePath | fromParts(const QStringView scheme, const QStringView host, const QStringView path) |
| Utils::FilePath | fromPathComponents(const QList<QStringView> &components) |
| Utils::FilePath | fromPathPart(const QStringView path) |
| Utils::FilePath | fromSettings(const QVariant &variant) |
| 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) |
| void | iterateDirectories(const Utils::FilePaths &dirs, const Utils::FilePath::IterateDirCallback &callBack, const Utils::FileFilter &filter) |
| void | removeDuplicates(Utils::FilePaths &files) |
| void | sort(Utils::FilePaths &files) |
| std::vector<Utils::Result<std::unique_ptr<Utils::FilePathWatcher>>> | watch(const Utils::FilePaths &paths) |
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::toUrlishString()
Converts the FilePath to a scheme://host/path string.
Mostly used in legacy code and for debugging reasons.
In almost all cases, use of one of the more specialized conversion 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 toUrlishString() 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
Utils::FilePath FilePath::absoluteFilePath() const
Returns an absolute version of this path, resolving "." and ".." components.
If this path is already absolute, it is cleaned and returned as-is. If this path is relative, it is resolved against the current working directory.
See also absolutePath() and cleanPath().
Utils::FilePath FilePath::absolutePath() const
Returns the absolute path of the parent directory of this path.
If this is a relative path, it is resolved against the current working directory first.
See also absoluteFilePath() and parentDir().
Utils::FileStreamHandle FilePath::asyncCopy(const Utils::Continuation<> &cont, const Utils::FilePath &target) const
Asynchronously copies this file to target, invoking cont on completion.
Returns a handle that can be used to cancel the operation.
See also asyncRead() and asyncWrite().
Utils::FileStreamHandle FilePath::asyncRead(const Utils::Continuation<QByteArray> &cont) const
Asynchronously reads this file, invoking cont with the file contents on completion.
Returns a handle that can be used to cancel the operation.
See also asyncWrite() and asyncCopy().
Utils::FileStreamHandle FilePath::asyncWrite(const Utils::Continuation<qint64> &cont, const QByteArray &data) const
Asynchronously writes data to this file, invoking cont with the number of bytes written on completion.
Returns a handle that can be used to cancel the operation.
See also asyncRead() and asyncCopy().
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.
qint64 FilePath::bytesAvailable() const
Returns the number of bytes available on the file system containing this path, or 0 if the information cannot be determined.
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 case sensitivity applicable to this path.
This is currently based on the host OS for local paths. For device (remote) 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()
Resets this FilePath to an empty state, clearing scheme, host, and path.
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.
Utils::Result<> FilePath::copyFile(const Utils::FilePath &target) const
Copies this file to target.
Cross-device copying (that is, between different scheme/host combinations) is handled by reading all content and writing it to the target. Returns a successful Result<> on success, or an error result on failure.
See also copyRecursively() and renameFile().
Utils::Result<> FilePath::copyRecursively(const Utils::FilePath &target) const
Recursively copies the directory or file at this path to target.
Returns a successful Result<> on success, or an error result on failure.
See also copyFile() and renameFile().
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().
Utils::Result<> FilePath::createSymLink(const Utils::FilePath &symLink) const
Creates a symbolic link symLink pointing to this file path.
Note: On Windows, this function will not work unless you have admin rights or developer mode is enabled.
Utils::Result<Utils::FilePath> FilePath::createTempDir() const
Creates a new temporary directory using this path as a template.
Returns the path of the created temporary directory on success, or an error result. The caller is responsible for removing the directory when no longer needed.
Utils::Result<Utils::FilePath> FilePath::createTempFile() const
Creates a new temporary file using this path as a template.
Returns the path of the created temporary file on success, or an error result. The caller is responsible for deleting the file when no longer needed.
[static] Utils::FilePath FilePath::currentWorkingPath()
Returns the current working directory as a FilePath.
Utils::Environment FilePath::deviceEnvironment() const
Returns the environment of the device this path belongs to.
For local paths, this is the system environment. For remote paths, the device's environment is queried. Asserts and returns an empty environment on failure.
See also deviceEnvironmentWithError().
Utils::Result<Utils::Environment> FilePath::deviceEnvironmentWithError() const
Returns the environment of the device this path belongs to, or an error result on failure.
See also deviceEnvironment().
Utils::FilePaths FilePath::devicePathEnvironmentVariable() const
Returns the PATH directories of the device this path belongs to, with the scheme and host of this path applied to each entry.
Utils::FilePaths FilePath::dirEntries(QDir::Filters filters) const
Returns the entries of the directory matching filters.
See also iterateDirectory().
Utils::FilePaths FilePath::dirEntries(const Utils::FileFilter &filter, QDir::SortFlags sort = QDir::NoSort) const
Returns the entries of the directory matching filter, optionally sorted by sort.
See also iterateDirectory().
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.
bool FilePath::ensureExistingFile() const
Creates the file at this path if it does not already exist.
Returns true if the file exists or was successfully created, false otherwise.
Utils::Result<> FilePath::ensureReachable(const Utils::FilePath &other) const
Ensures that other is reachable from this device.
For local paths, this succeeds only if other is also local. For remote paths, the device hook is invoked to set up any required connection.
Returns a successful Result<> if other is reachable, or an error result otherwise.
Utils::Result<> FilePath::ensureWritableDir() const
Re-uses or creates a directory at this location.
Returns a successful Result<> if the directory exists and is writable afterwards, or an error result describing why the directory could not be created or accessed.
See also createDir().
bool FilePath::equalsCaseSensitive(const Utils::FilePath &other) const
Returns true if this file path compares equal to other case-sensitively. This is relevant on semi-case sensitive systems like Windows with NTFS.
See also QTCREATORBUG-30846.
bool FilePath::exists() const
Returns a bool indicating whether a file or directory with this FilePath exists.
Utils::Result<QByteArray> FilePath::fileContents(qint64 maxSize = -1, qint64 offset = 0) const
Reads and returns the contents of the file.
If maxSize is not -1, at most maxSize bytes are read. Reading starts at byte position offset.
Returns an error result if the file could not be read.
See also writeFileContents().
QString FilePath::fileName() const
Returns the last path component (the file name) as a QString, without any directory path.
See also fileNameView(), baseName(), and suffix().
QStringView FilePath::fileNameView() const
Returns the last path component (the file name) as a QStringView, without any directory path.
See also fileName().
QString FilePath::fileNameWithPathComponents(int pathComponents) const
Returns the file name with the pathComponents leading directory components included.
- If pathComponents is 0, only the file name is returned.
- If pathComponents is -1, the full path is returned.
- If there are fewer path components than pathComponents, the full URL-ish string is returned.
qint64 FilePath::fileSize() const
Returns the size of the file in bytes, or 0 if the size cannot be determined.
[static] Utils::FilePath FilePath::fromFileInfo(const QFileInfo &info)
Constructs a FilePath from info.
[static] Utils::FilePath FilePath::fromParts(const QStringView scheme, const QStringView host, const QStringView path)
Constructs a FilePath from the scheme, host, and path parts.
See also scheme(), host(), and path().
[static] Utils::FilePath FilePath::fromPathComponents(const QList<QStringView> &components)
Constructs a local FilePath by joining the given path components with '/'.
If components is empty, an empty FilePath is returned. If the first component is '/', the resulting path will be absolute.
See also pathComponents().
[static] Utils::FilePath FilePath::fromPathPart(const QStringView path)
Constructs a local FilePath with only the path part set to path. The scheme and host parts are left empty.
[static] Utils::FilePath FilePath::fromSettings(const QVariant &variant)
Constructs a FilePath from the QVariant variant as stored by toSettings().
See also toSettings() and fromVariant().
[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 toFSPathString, toUserOutput, 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 toUrl().
[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().
QString FilePath::group() const
Returns the name of the group owning this file, or an empty string if not available.
See also groupId() and owner().
uint FilePath::groupId() const
Returns the numeric group ID of the group owning this file, or 0 if not available.
See also group() and ownerId().
bool FilePath::hasHardLinks() const
Returns true if the file at this path has more than one hard link.
QStringView FilePath::host() const
Returns the host part of the FilePath, identifying the remote file system.
Returns an empty QStringView for local paths.
See also scheme(), path(), and fromParts().
Utils::FilePath FilePath::intern() const
Returns a copy with interned data.
bool FilePath::isAbsolutePath() const
Checks whether the path is absolute.
Returns true if the path starts with a slash, or with a letter and a colon, or with a colon and a slash.
Note: This is independent of the platform on which Qt Creator currently runs, so this does not necessarily match the platform's definition of an absolute path. Use with care, and try to avoid.
See also isRelativePath().
bool FilePath::isChildOf(const Utils::FilePath &s) const
Returns whether FilePath is a child of s.
bool FilePath::isEmpty() const
Returns true if the path part is empty. The scheme and host are not considered.
bool FilePath::isExecutableFile() const
Returns a bool indicating whether this is an executable file.
bool FilePath::isLocal() const
Returns true if this path refers to the local file system (no scheme, or the scheme "file").
bool FilePath::isNewerThan(const QDateTime &timeStamp) const
Returns true if this file or directory is newer than timeStamp.
For a directory, the check recurses into all contained files and returns true if any of them is newer than timeStamp.
bool FilePath::isRelativePath() const
Checks whether the path is relative.
Returns true if the path starts neither with a slash, nor with a letter and a colon, nor with a colon and a slash.
Note: This is independent of the platform on which Qt Creator currently runs, so this does not necessarily match the platform's definition of a relative path. Use with care, and try to avoid.
See also isAbsolutePath().
bool FilePath::isResourceFile() const
Returns true if this path refers to a Qt resource file, that is, if it has the "qrc" scheme or its path starts with ':'.
bool FilePath::isRootPath() const
Returns true if this path is a filesystem root (for example, "/" on Unix or "C:/" on Windows).
bool FilePath::isSameDevice(const Utils::FilePath &other) const
Returns true if other refers to the same device (scheme and host) as this path.
bool FilePath::isSameExecutable(const Utils::FilePath &other) const
Returns true if other refers to the same executable as this path, considering possible platform-specific suffixes such as ".exe" or ".bat".
See also isSameFile().
bool FilePath::isSameFile(const Utils::FilePath &other) const
Returns true if other refers to the same file as this path.
Two paths can refer to the same file even if they are not equal strings, for example when one uses a symlink or a different access method. This function uses the device's file ID for comparison when the paths differ.
See also isSameExecutable() and isSameDevice().
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.
[static] void FilePath::iterateDirectories(const Utils::FilePaths &dirs, const Utils::FilePath::IterateDirCallback &callBack, const Utils::FileFilter &filter)
Runs callBack on each directory entry matching filter in each of the dirs.
See also iterateDirectory().
void FilePath::iterateDirectory(const Utils::FilePath::IterateDirCallback &callBack, const Utils::FileFilter &filter) const
Runs callBack on each directory entry matching the filter.
QDateTime FilePath::lastModified() const
Returns the date and time when this file or directory was last modified.
Returns an invalid QDateTime if the modification time cannot be determined.
Utils::Result<Utils::FilePath> FilePath::localSource() const
Returns a FilePath that represents the same file accessible from the local file system, or an error result if no such mapping is available.
For local paths, returns *this. For remote paths, the device hook is consulted.
Utils::Result<> FilePath::makeWritable() const
Adds write permission for the owner of this file.
Returns a successful Result<> on success, or an error result on failure.
See also setPermissions() and permissions().
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::OsType FilePath::osType() const
Returns the OS type of the device this path belongs to.
For local paths, returns the host OS type. For remote paths, queries the device's OS type.
QString FilePath::owner() const
Returns the name of the user owning this file, or an empty string if not available.
See also ownerId() and group().
uint FilePath::ownerId() const
Returns the numeric user ID of the owner of this file, or 0 if not available.
See also owner() and groupId().
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.
QString FilePath::path() const
Returns the path part of the FilePath as a QString, using forward slashes.
See also pathView(), scheme(), and host().
Utils::FilePath FilePath::pathAppended(const QString &path) const
Returns this path with path appended, joined by a '/'.
Backslashes in path are normalized to forward slashes. This is equivalent to operator/(path).
See also stringAppended() and operator/().
QChar FilePath::pathComponentSeparator() const
Returns the path component separator for the OS of this path: '\' on Windows, '/' elsewhere.
QList<QStringView> FilePath::pathComponents() const
Returns the path split into its components at '/' boundaries.
On Windows paths, the drive letter (for example "C:") and root slash are returned as separate leading components.
An initial '/' is returned as a single '/' component.
See also fromPathComponents().
QChar FilePath::pathListSeparator() const
Returns the PATH list separator for the OS of this path: ';' on Windows, ':' elsewhere.
QStringView FilePath::pathView() const
Returns the path part of the FilePath as a QStringView, using forward slashes.
See also path(), scheme(), and host().
QFileDevice::Permissions FilePath::permissions() const
Returns the permissions of this file or directory.
Returns an empty set of permissions if they cannot be determined.
See also setPermissions() and makeWritable().
std::optional<Utils::FilePath> FilePath::prefixRemoved(const QString &str) const
Returns this path with str removed from the beginning of the path part, or std::nullopt if the path does not start with str.
Utils::TextEncoding FilePath::processStdErrEncoding() const
Returns the text encoding used by processes on the device for standard error.
Utils::TextEncoding FilePath::processStdOutEncoding() const
Returns the text encoding used by processes on the device for standard output.
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
Returns the relative path from parent to this.
Returns an empty FilePath if this is not a child of parent. The result never starts with "../". If this is not under parent, use relativePathFromDir() instead.
See also relativePathFromDir() and isChildOf().
QString FilePath::relativeNativePathFromDir(const Utils::FilePath &anchorDir) const
Returns the relative path from anchorDir to this, using the native path separator of the associated OS.
Example usage:
FilePath filePath("C:/foo/b/ar/file.txt");
QString relativePath = filePath.relativePathFromDir(FilePath("C:\\foo\\c"));
qDebug() << relativePath;The debug output will be "..\b\ar\file.txt".
See also relativePathFromDir().
QString FilePath::relativePathFromDir(const Utils::FilePath &anchorDir) const
Returns the relative path of FilePath from the directory anchorDir. FilePath and anchor directory may be files or directories.
Example usage:
FilePath filePath("/foo/b/ar/file.txt");
QString relativePath = filePath.relativePathFromDir(FilePath("/foo/c"));
qDebug() << relativePath;The debug output will be "../b/ar/file.txt".
See also relativeNativePathFromDir().
[static] void FilePath::removeDuplicates(Utils::FilePaths &files)
Removes duplicate entries from files in-place, preserving order.
Utils::Result<> FilePath::removeFile() const
Removes the file at this path.
Returns a successful Result<> on success, or an error result on failure.
See also removeRecursively().
Utils::Result<> FilePath::removeRecursively() const
Removes the directory this filePath refers too and its subdirectories recursively.
Utils::Result<> FilePath::renameFile(const Utils::FilePath &target) const
Moves (renames) this file to target.
If target is on the same device, a native rename is used. Otherwise, the file is copied and the source is deleted. Returns a successful Result<> on success, or an error result on failure.
See also copyFile() and removeFile().
Utils::FilePath FilePath::resolvePath(const QString &tail) const
Appends tail to this if tail is a relative path, or replaces only the path part with tail if it is absolute (preserving this path's scheme and host).
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::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.
QStringView FilePath::scheme() const
Returns the scheme part of the FilePath, such as "docker" or "ssh".
Returns an empty QStringView for local paths.
See also host(), path(), and fromParts().
Utils::FilePaths FilePath::searchAllInDirectories(const Utils::FilePaths &dirs, const Utils::FilePathPredicate &filter = {}, Utils::FilePath::MatchScope matchScope = WithAnySuffix) const
Returns all executables matching this file name found in any of the dirs, optionally filtered by filter and with executable suffix handling controlled by matchScope.
See also searchInDirectories() and searchAllInPath().
Utils::FilePaths FilePath::searchAllInPath() const
Searches for all executables with this name in the PATH of the associated device.
Utils::FilePaths FilePath::searchAllInPath(const Utils::FilePaths &additionalDirs, Utils::FilePath::PathAmending amending = AppendToPath, const Utils::FilePathPredicate &filter = {}, Utils::FilePath::MatchScope matchScope = WithAnySuffix) const
Searches for all executables with this name in the PATH of the associated device, augmented with additionalDirs according to amending. Optionally filters results with filter and handles suffixes according to matchScope.
See also searchInPath() and searchAllInDirectories().
void FilePath::searchHereAndInParents(const std::function<IterationPolicy (const FilePath &)> &constraint) const
Walks this directory and its ancestor directories, invoking constraint on each.
Iteration stops when constraint returns IterationPolicy::Stop or the root is reached.
Utils::FilePath FilePath::searchHereAndInParents(const QString &fileName, QDir::Filter type) const
Searches for a file or directory named fileName of type type in this directory and all of its ancestor directories.
Returns the first match found, or an empty FilePath if none is found.
See also searchHereAndInParents(const QStringList &, QDir::Filter).
Utils::FilePath FilePath::searchHereAndInParents(const QStringList &fileNames, QDir::Filter type) const
Searches for any file or directory in fileNames of type type in this directory and all of its ancestor directories.
Returns the first match found, or an empty FilePath if none is found.
See also searchHereAndInParents(const QString &, QDir::Filter).
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"))Utils::FilePath FilePath::searchInPath() const
Searches for this executable in the PATH of the associated device.
Utils::FilePath FilePath::searchInPath(const Utils::FilePaths &additionalDirs, Utils::FilePath::PathAmending amending = AppendToPath, const Utils::FilePathPredicate &filter = {}, Utils::FilePath::MatchScope matchScope = WithAnySuffix) const
Searches for this executable in the PATH of the associated device, augmented with additionalDirs according to amending. Optionally filters results with filter and handles suffixes according to matchScope.
Returns an empty FilePath if the executable is not found.
See also searchAllInPath() and searchInDirectories().
void FilePath::setParts(const QStringView scheme, const QStringView host, const QStringView path)
Sets the scheme, host, and path parts of this FilePath to scheme, host, and path.
See also fromParts(), scheme(), host(), and path().
Utils::Result<> FilePath::setPermissions(QFileDevice::Permissions permissions) const
Sets the permissions of this file or directory to permissions.
Returns a successful Result<> on success, or an error result on failure.
See also permissions() and makeWritable().
QString FilePath::shortNativePath() const
Returns the path with native separators, with the home directory abbreviated to '~' on Unix.
Equivalent to toUserOutput(), but replaces the home directory prefix with '~' on Unix.
[static] void FilePath::sort(Utils::FilePaths &files)
Sorts files lexicographically by scheme, then host, then path.
bool FilePath::startsWith(const QString &s) const
Returns whether path() starts with s.
bool FilePath::startsWithDriveLetter() const
Returns true if the path starts with a Windows drive letter followed by a colon, for example: "C:".
Utils::FilePath FilePath::stringAppended(const QString &str) const
Returns a re-parsed path with str appended directly to the URL-ish string representation, without inserting a separator.
See also pathAppended().
QString FilePath::suffix() 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.
See also suffixView().
QStringView FilePath::suffixView() const
Returns the suffix (extension) of the file as QStringView.
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.
std::optional<Utils::FilePath> FilePath::tailRemoved(const QString &str) const
Returns this path with str removed from the end of the path part, or std::nullopt if the path does not end with str.
Utils::Result<Utils::FilePath> FilePath::tmpDir() const
Returns the temporary directory for the device this path belongs to.
For local paths, this is equivalent to QDir::tempPath(). For remote devices, the TMPDIR, TEMP, or TMP environment variables are checked in order, and "/tmp" is used as a fallback on non-Windows devices.
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.
QVariant FilePath::toSettings() const
Returns the FilePath as a QVariant suitable for storing in settings.
See also fromSettings() and toVariant().
QUrl FilePath::toUrl() const
Returns this FilePath as QUrl.
QString FilePath::toUrlishString() 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 QDir 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.
[static] std::vector<Utils::Result<std::unique_ptr<Utils::FilePathWatcher>>> FilePath::watch(const Utils::FilePaths &paths)
Returns a FilePathWatcher for each given path.
The returned FilePathWatcher emits its signal when the file at this path is modified, renamed, or deleted. The signal is emitted in the calling thread. If called from a non-main thread, it might take a while until the signal starts to be emitted.
See also FilePathWatcher.
Utils::FilePath FilePath::withExecutableSuffix() const
Returns a copy of this path with the platform-specific executable suffix appended, such as ".exe" on Windows.
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"))Utils::FilePath FilePath::withSuffix(const QString &suffix) const
Returns a copy of this path with suffix appended to the path string verbatim.
Use this for appending suffixes like file extensions. For directory appending, use pathAppended() or operator/() instead.
QString FilePath::withTildeHomePath() const
Returns the path with the user's home directory prefix replaced by '~' on Unix, equivalent to calling toUrlishString() after cleaning.
On Windows or for remote paths, the toUrlishString() result is returned unchanged.
Utils::Result<qint64> FilePath::writeFileContents(const QByteArray &data) const
Writes data to the file, replacing any existing content.
Returns the number of bytes written on success, or an error result.
See also fileContents().
Utils::FilePath FilePath::operator/(const QString &str) const
Returns this path with str appended as a path component, equivalent to pathAppended().
See also pathAppended().
Utils::FilePath &FilePath::operator/=(const QString &str)
Appends str as a path component to this path in-place and returns a reference to this.
See also pathAppended() and operator/().
Copyright © The Qt Company Ltd. and other contributors. 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.