QFileInfo类

The QFileInfo class provides system-independent file information. More...

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

Note: All functions in this class are reentrant.

Public Functions

 QFileInfo(const QFileInfo &fileinfo)
 QFileInfo(const QDir &dir, const QString &file)
 QFileInfo(const QFile &file)
 QFileInfo(const QString &file)
 QFileInfo()
QFileInfo &operator=(QFileInfo &&other)
QFileInfo &operator=(const QFileInfo &fileinfo)
 ~QFileInfo()
QDirabsoluteDir() const
QStringabsoluteFilePath() const
QStringabsolutePath() const
QStringbaseName() const
QDateTimebirthTime() const
QStringbundleName() const
boolcaching() const
QStringcanonicalFilePath() const
QStringcanonicalPath() const
QStringcompleteBaseName() const
QStringcompleteSuffix() const
QDirdir() const
boolexists() const
QStringfileName() const
QStringfilePath() const
QDateTimefileTime(QFile::FileTime time) const
QStringgroup() const
uintgroupId() const
boolisAbsolute() const
boolisBundle() const
boolisDir() const
boolisExecutable() const
boolisFile() const
boolisHidden() const
boolisNativePath() const
boolisReadable() const
boolisRelative() const
boolisRoot() const
boolisSymLink() const
boolisWritable() const
QDateTimelastModified() const
QDateTimelastRead() const
boolmakeAbsolute()
QDateTimemetadataChangeTime() const
QStringowner() const
uintownerId() const
QStringpath() const
boolpermission(QFile::Permissions permissions) const
QFile::Permissionspermissions() const
voidrefresh()
voidsetCaching(bool enable)
voidsetFile(const QString &file)
voidsetFile(const QFile &file)
voidsetFile(const QDir &dir, const QString &file)
qint64size() const
QStringsuffix() const
voidswap(QFileInfo &other)
QStringsymLinkTarget() const
booloperator!=(const QFileInfo &fileinfo) const
booloperator==(const QFileInfo &fileinfo) const

Static Public Members

boolexists(const QString &file)

Related Non-Members

typedefQFileInfoList

详细说明

QFileInfo提供有关文件在文件系统中的名称和位置(路径),其访问权限以及它是目录链接还是符号链接等信息。文件的大小和上次修改/读取的时间也可用。QFileInfo也可用于获取有关Qt 资源的信息

QFileInfo可以指向与相对或绝对文件路径的文件。绝对文件路径以目录分隔符“ /”(或Windows上的驱动器规范)开头。相对文件名以目录名或文件名开头,并指定相对于当前工作目录的路径。绝对路径的一个示例是字符串“ / tmp / quartz”。相对路径可能类似于“ src / fatlib”。您可以使用函数isRelative()来检查QFileInfo是使用相对还是绝对文件路径。您可以调用函数makeAbsolute()将相对QFileInfo的路径转换为绝对路径。

QFileInfo处理的文件是在构造函数中设置的,或者以后是通过setFile()设置的。使用exist()查看文件是否存在,使用size()获取其大小。

通过isFile(),isDir()和isSymLink()获得文件的类型。该symLinkTarget()函数提供该文件的符号链接指向的名字。

在Unix(包括macOS和iOS)上,此类中的属性getter函数返回目标文件的时间和大小(而非符号链接)之类的属性,因为Unix透明地处理符号链接。使用QFile打开符号链接可以有效地打开链接的目标。例如:

#ifdef Q_OS_UNIX

QFileInfo info1("/home/bob/bin/untabify");
info1.isSymLink();          // returns true
info1.absoluteFilePath();   // returns "/home/bob/bin/untabify"
info1.size();               // returns 56201
info1.symLinkTarget();      // returns "/opt/pretty++/bin/untabify"

QFileInfo info2(info1.symLinkTarget());
info2.isSymLink();          // returns false
info2.absoluteFilePath();   // returns "/opt/pretty++/bin/untabify"
info2.size();               // returns 56201

#endif

在Windows上,符号链接(快捷方式)是.lnk文件。与Unix系统类似,属性获取器返回目标文件的大小,而不是.lnk文件本身。请注意,此行为已被弃用,并且可能会在Qt的将来版本中删除,此后该.lnk文件将被视为常规文件。

#ifdef Q_OS_WIN

QFileInfo info1("C:\\Documents and Settings\\Bob\\untabify.lnk");
info1.isSymLink();          // returns true
info1.absoluteFilePath();   // returns "C:/Documents and Settings/Bob/untabify.lnk"
info1.size();               // returns 743
info1.symLinkTarget();      // returns "C:/Pretty++/untabify"

QFileInfo info2(info1.symLinkTarget());
info2.isSymLink();          // returns false
info2.absoluteFilePath();   // returns "C:/Pretty++/untabify"
info2.size();               // returns 63942

#endif

可以使用path()和fileName()提取文件名的元素。的文件名()的部件都可以用被提取baseName的(),后缀()或completeSuffix()。由Qt类创建的目录的QFileInfo对象将没有尾随文件分隔符。如果您希望在自己的文件信息对象中使用尾随分隔符,只需在提供给构造函数或setFile()的文件名后附加一个。

该文件的日期是由返回()创建的,上次更改时间(),lastRead()和FILETIME()。有关文件访问权限的信息可通过isReadable(),isWritable()和isExecutable()获得。可通过owner(),ownerId(),group()和groupId()获得文件的所有权。您可以使用权限()函数在单个语句中检查文件的权限和所有权。

注意:在NTFS文件系统上,出于性能原因,默认情况下禁用所有权和权限检查。要启用它,请包含以下行:

extern Q_CORE_EXPORT int qt_ntfs_permission_lookup;

然后通过增加和减少qt_ntfs_permission_lookup1来打开和关闭权限检查。

qt_ntfs_permission_lookup++; // turn checking on
qt_ntfs_permission_lookup--; // turn it off again

性能问题

QFileInfo的某些功能查询文件系统,但是出于性能原因,某些功能仅对文件名本身起作用。例如:要返回相对文件名的绝对路径,absolutePath()必须查询文件系统。该路径()函数,但是,可以对文件名直接工作,所以它比较快。

注意:为了提高性能,QFileInfo缓存有关文件的信息。

因为文件可以被其他用户或程序甚至同一程序的其他部分更改,所以有一个刷新文件信息的函数:refresh()。如果要关闭QFileInfo的缓存,并在每次您从文件系统请求信息时强制其访问文件系统,请调用setCaching(false)。

另请参见QDirQFile

Member Function Documentation

QFileInfo::QFileInfo(const QFileInfo &fileinfo)

Constructs a new QFileInfo that is a copy of the given fileinfo.

QFileInfo::QFileInfo(const QDir &dir, const QString &file)

Constructs a new QFileInfo that gives information about the given file in the directory dir.

If dir has a relative path, the QFileInfo will also have a relative path.

If file is an absolute path, then the directory specified by dir will be disregarded.

See also isRelative().

QFileInfo::QFileInfo(const QFile &file)

Constructs a new QFileInfo that gives information about file file.

If the file has a relative path, the QFileInfo will also have a relative path.

See also isRelative().

QFileInfo::QFileInfo(const QString &file)

Constructs a new QFileInfo that gives information about the given file. The file can also include an absolute or relative path.

See also setFile(), isRelative(), QDir::setCurrent(), and QDir::isRelativePath().

QFileInfo::QFileInfo()

Constructs an empty QFileInfo object.

Note that an empty QFileInfo object contain no file reference.

See also setFile().

QFileInfo &QFileInfo::operator=(QFileInfo &&other)

Move-assigns other to this QFileInfo instance.

This function was introduced in Qt 5.2.

QFileInfo &QFileInfo::operator=(const QFileInfo &fileinfo)

Makes a copy of the given fileinfo and assigns it to this QFileInfo.

QFileInfo::~QFileInfo()

Destroys the QFileInfo and frees its resources.

QDir QFileInfo::absoluteDir() const

Returns the file's absolute path as a QDir object.

See also dir(), filePath(), fileName(), and isRelative().

QString QFileInfo::absoluteFilePath() const

Returns an absolute path including the file name.

The absolute path name consists of the full path and the file name. On Unix this will always begin with the root, '/', directory. On Windows this will always begin 'D:/' where D is a drive letter, except for network shares that are not mapped to a drive letter, in which case the path will begin '//sharename/'. QFileInfo will uppercase drive letters. Note that QDir does not do this. The code snippet below shows this.

    QFileInfo fi("c:/temp/foo"); => fi.absoluteFilePath() => "C:/temp/foo"

This function returns the same as filePath(), unless isRelative() is true. In contrast to canonicalFilePath(), symbolic links or redundant "." or ".." elements are not necessarily removed.

Warning: If filePath() is empty the behavior of this function is undefined.

See also filePath(), canonicalFilePath(), and isRelative().

QString QFileInfo::absolutePath() const

Returns a file's path absolute path. This doesn't include the file name.

On Unix the absolute path will always begin with the root, '/', directory. On Windows this will always begin 'D:/' where D is a drive letter, except for network shares that are not mapped to a drive letter, in which case the path will begin '//sharename/'.

In contrast to canonicalPath() symbolic links or redundant "." or ".." elements are not necessarily removed.

Warning: If filePath() is empty the behavior of this function is undefined.

See also absoluteFilePath(), path(), canonicalPath(), fileName(), and isRelative().

QString QFileInfo::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.

Example:

QFileInfo fi("/tmp/archive.tar.gz");
QString base = fi.baseName();  // base = "archive"

The base name of a file is computed equally on all platforms, independent of file naming conventions (e.g., ".bashrc" on Unix has an empty base name, and the suffix is "bashrc").

See also fileName(), suffix(), completeSuffix(), and completeBaseName().

QDateTime QFileInfo::birthTime() const

Returns the date and time when the file was created / born.

If the file birth time is not available, this function returns an invalid QDateTime.

If the file is a symlink, the time of the target file is returned (not the symlink).

This function was introduced in Qt 5.10.

See also lastModified(), lastRead(), and metadataChangeTime().

QString QFileInfo::bundleName() const

Returns the name of the bundle.

On macOS and iOS this returns the proper localized name for a bundle if the path isBundle(). On all other platforms an empty QString is returned.

Example:

QFileInfo fi("/Applications/Safari.app");
QString bundle = fi.bundleName();                // name = "Safari"

This function was introduced in Qt 4.3.

See also isBundle(), filePath(), baseName(), and suffix().

bool QFileInfo::caching() const

Returns true if caching is enabled; otherwise returns false.

See also setCaching() and refresh().

QString QFileInfo::canonicalFilePath() const

Returns the canonical path including the file name, i.e. an absolute path without symbolic links or redundant "." or ".." elements.

If the file does not exist, canonicalFilePath() returns an empty string.

See also filePath(), absoluteFilePath(), and dir().

QString QFileInfo::canonicalPath() const

Returns the file's path canonical path (excluding the file name), i.e. an absolute path without symbolic links or redundant "." or ".." elements.

If the file does not exist, canonicalPath() returns an empty string.

See also path() and absolutePath().

QString QFileInfo::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.

Example:

QFileInfo fi("/tmp/archive.tar.gz");
QString base = fi.completeBaseName();  // base = "archive.tar"

See also fileName(), suffix(), completeSuffix(), and baseName().

QString QFileInfo::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 '.'.

Example:

QFileInfo fi("/tmp/archive.tar.gz");
QString ext = fi.completeSuffix();  // ext = "tar.gz"

See also fileName(), suffix(), baseName(), and completeBaseName().

QDir QFileInfo::dir() const

Returns the path of the object's parent directory as a QDir object.

Note: The QDir returned always corresponds to the object's parent directory, even if the QFileInfo represents a directory.

For each of the following, dir() returns the QDir "~/examples/191697".

    QFileInfo fileInfo1("~/examples/191697/.");
    QFileInfo fileInfo2("~/examples/191697/..");
    QFileInfo fileInfo3("~/examples/191697/main.cpp");

For each of the following, dir() returns the QDir ".".

    QFileInfo fileInfo4(".");
    QFileInfo fileInfo5("..");
    QFileInfo fileInfo6("main.cpp");

See also absolutePath(), filePath(), fileName(), isRelative(), and absoluteDir().

bool QFileInfo::exists() const

Returns true if the file exists; otherwise returns false.

Note: If the file is a symlink that points to a non-existing file, false is returned.

[static]bool QFileInfo::exists(const QString &file)

Returns true if the file exists; otherwise returns false.

Note: If file is a symlink that points to a non-existing file, false is returned.

Note: Using this function is faster than using QFileInfo(file).exists() for file system access.

This function was introduced in Qt 5.2.

QString QFileInfo::fileName() const

Returns the name of the file, excluding the path.

Example:

QFileInfo fi("/tmp/archive.tar.gz");
QString name = fi.fileName();                // name = "archive.tar.gz"

Note that, if this QFileInfo object is given a path ending in a slash, the name of the file is considered empty.

See also isRelative(), filePath(), baseName(), and suffix().

QString QFileInfo::filePath() const

Returns the file name, including the path (which may be absolute or relative).

See also absoluteFilePath(), canonicalFilePath(), and isRelative().

QDateTime QFileInfo::fileTime(QFile::FileTime time) const

Returns the file time specified by time. If the time cannot be determined, an invalid date time is returned.

If the file is a symlink, the time of the target file is returned (not the symlink).

This function was introduced in Qt 5.10.

See also QFile::FileTime and QDateTime::isValid().

QString QFileInfo::group() const

Returns the group of the file. On Windows, on systems where files do not have groups, or if an error occurs, an empty string is returned.

This function can be time consuming under Unix (in the order of milliseconds).

If the file is a symlink, this function returns the owning group of the target (not the symlink).

See also groupId(), owner(), and ownerId().

uint QFileInfo::groupId() const

Returns the id of the group the file belongs to.

On Windows and on systems where files do not have groups this function always returns (uint) -2.

If the file is a symlink, this function returns the id of the group owning the target (not the symlink).

See also group(), owner(), and ownerId().

bool QFileInfo::isAbsolute() const

Returns true if the file path name is absolute, otherwise returns false if the path is relative.

See also isRelative().

bool QFileInfo::isBundle() const

Returns true if this object points to a bundle or to a symbolic link to a bundle on macOS and iOS; otherwise returns false.

If the file is a symlink, this function returns true if the target is a bundle (not the symlink).

This function was introduced in Qt 4.3.

See also isDir(), isSymLink(), and isFile().

bool QFileInfo::isDir() const

Returns true if this object points to a directory or to a symbolic link to a directory; otherwise returns false.

If the file is a symlink, this function returns true if the target is a directory (not the symlink).

See also isFile(), isSymLink(), and isBundle().

bool QFileInfo::isExecutable() const

Returns true if the file is executable; otherwise returns false.

If the file is a symlink, this function returns true if the target is executable (not the symlink).

See also isReadable(), isWritable(), and permission().

bool QFileInfo::isFile() const

Returns true if this object points to a file or to a symbolic link to a file. Returns false if the object points to something which isn't a file, such as a directory.

If the file is a symlink, this function returns true if the target is a regular file (not the symlink).

See also isDir(), isSymLink(), and isBundle().

bool QFileInfo::isHidden() const

Returns true if this is a `hidden' file; otherwise returns false.

Note: This function returns true for the special entries "." and ".." on Unix, even though QDir::entryList threats them as shown. And note that, since this function inspects the file name, on Unix it will inspect the name of the symlink, if this file is a symlink, not the target's name.

On Windows, this function returns true if the target file is hidden (not the symlink).

bool QFileInfo::isNativePath() const

Returns true if the file path can be used directly with native APIs. Returns false if the file is otherwise supported by a virtual file system inside Qt, such as the Qt Resource System.

Note: Native paths may still require conversion of path separators and character encoding, depending on platform and input requirements of the native API.

This function was introduced in Qt 5.0.

See also QDir::toNativeSeparators(), QFile::encodeName(), filePath(), absoluteFilePath(), and canonicalFilePath().

bool QFileInfo::isReadable() const

Returns true if the user can read the file; otherwise returns false.

If the file is a symlink, this function returns true if the target is readable (not the symlink).

Note: If the NTFS permissions check has not been enabled, the result on Windows will merely reflect whether the file exists.

See also isWritable(), isExecutable(), and permission().

bool QFileInfo::isRelative() const

Returns true if the file path name is relative, otherwise returns false if the path is absolute (e.g. under Unix a path is absolute if it begins with a "/").

See also isAbsolute().

bool QFileInfo::isRoot() const

Returns true if the object points to a directory or to a symbolic link to a directory, and that directory is the root directory; otherwise returns false.

Returns true if this object points to a symbolic link; otherwise returns false.

Symbolic links exist on Unix (including macOS and iOS) and Windows and are typically created by the ln -s or mklink commands, respectively. Opening a symbolic link effectively opens the link's target.

In addition, true will be returned for shortcuts (*.lnk files) on Windows. This behavior is deprecated and will likely change in a future version of Qt. Opening those will open the .lnk file itself.

Example:

QFileInfo info(fileName);
if (info.isSymLink())
    fileName = info.symLinkTarget();

Note: If the symlink points to a non existing file, exists() returns false.

See also isFile(), isDir(), and symLinkTarget().

bool QFileInfo::isWritable() const

Returns true if the user can write to the file; otherwise returns false.

If the file is a symlink, this function returns true if the target is writeable (not the symlink).

Note: If the NTFS permissions check has not been enabled, the result on Windows will merely reflect whether the file is marked as Read Only.

See also isReadable(), isExecutable(), and permission().

QDateTime QFileInfo::lastModified() const

Returns the date and local time when the file was last modified.

If the file is a symlink, the time of the target file is returned (not the symlink).

See also birthTime(), lastRead(), metadataChangeTime(), and fileTime().

QDateTime QFileInfo::lastRead() const

Returns the date and local time when the file was last read (accessed).

On platforms where this information is not available, returns the same as lastModified().

If the file is a symlink, the time of the target file is returned (not the symlink).

See also birthTime(), lastModified(), metadataChangeTime(), and fileTime().

bool QFileInfo::makeAbsolute()

Converts the file's path to an absolute path if it is not already in that form. Returns true to indicate that the path was converted; otherwise returns false to indicate that the path was already absolute.

See also filePath() and isRelative().

QDateTime QFileInfo::metadataChangeTime() const

Returns the date and time when the file metadata was changed. A metadata change occurs when the file is created, but it also occurs whenever the user writes or sets inode information (for example, changing the file permissions).

If the file is a symlink, the time of the target file is returned (not the symlink).

This function was introduced in Qt 5.10.

See also lastModified() and lastRead().

QString QFileInfo::owner() const

Returns the owner of the file. On systems where files do not have owners, or if an error occurs, an empty string is returned.

This function can be time consuming under Unix (in the order of milliseconds). On Windows, it will return an empty string unless the NTFS permissions check has been enabled.

If the file is a symlink, this function returns the owner of the target (not the symlink).

See also ownerId(), group(), and groupId().

uint QFileInfo::ownerId() const

Returns the id of the owner of the file.

On Windows and on systems where files do not have owners this function returns ((uint) -2).

If the file is a symlink, this function returns the id of the owner of the target (not the symlink).

See also owner(), group(), and groupId().

QString QFileInfo::path() const

Returns the file's path. This doesn't include the file name.

Note that, if this QFileInfo object is given a path ending in a slash, the name of the file is considered empty and this function will return the entire path.

See also filePath(), absolutePath(), canonicalPath(), dir(), fileName(), and isRelative().

bool QFileInfo::permission(QFile::Permissions permissions) const

Tests for file permissions. The permissions argument can be several flags of type QFile::Permissions OR-ed together to check for permission combinations.

On systems where files do not have permissions this function always returns true.

Note: The result might be inaccurate on Windows if the NTFS permissions check has not been enabled.

Example:

QFileInfo fi("/tmp/archive.tar.gz");
if (fi.permission(QFile::WriteUser | QFile::ReadGroup))
    qWarning("I can change the file; my group can read the file");
if (fi.permission(QFile::WriteGroup | QFile::WriteOther))
    qWarning("The group or others can change the file");

If the file is a symlink, this function checks the permissions of the target (not the symlink).

See also isReadable(), isWritable(), and isExecutable().

QFile::Permissions QFileInfo::permissions() const

Returns the complete OR-ed together combination of QFile::Permissions for the file.

Note: The result might be inaccurate on Windows if the NTFS permissions check has not been enabled.

If the file is a symlink, this function returns the permissions of the target (not the symlink).

void QFileInfo::refresh()

Refreshes the information about the file, i.e. reads in information from the file system the next time a cached property is fetched.

void QFileInfo::setCaching(bool enable)

If enable is true, enables caching of file information. If enable is false caching is disabled.

When caching is enabled, QFileInfo reads the file information from the file system the first time it's needed, but generally not later.

Caching is enabled by default.

See also refresh() and caching().

void QFileInfo::setFile(const QString &file)

Sets the file that the QFileInfo provides information about to file.

The file can also include an absolute or relative file path. Absolute paths begin with the directory separator (e.g. "/" under Unix) or 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.

Example:

QString absolute = "/local/bin";
QString relative = "local/bin";
QFileInfo absFile(absolute);
QFileInfo relFile(relative);

QDir::setCurrent(QDir::rootPath());
// absFile and relFile now point to the same file

QDir::setCurrent("/tmp");
// absFile now points to "/local/bin",
// while relFile points to "/tmp/local/bin"

See also isFile(), isRelative(), QDir::setCurrent(), and QDir::isRelativePath().

void QFileInfo::setFile(const QFile &file)

This is an overloaded function.

Sets the file that the QFileInfo provides information about to file.

If file includes a relative path, the QFileInfo will also have a relative path.

See also isRelative().

void QFileInfo::setFile(const QDir &dir, const QString &file)

This is an overloaded function.

Sets the file that the QFileInfo provides information about to file in directory dir.

If file includes a relative path, the QFileInfo will also have a relative path.

See also isRelative().

qint64 QFileInfo::size() const

Returns the file size in bytes. If the file does not exist or cannot be fetched, 0 is returned.

If the file is a symlink, the size of the target file is returned (not the symlink).

See also exists().

QString QFileInfo::suffix() const

Returns the suffix (extension) of the file.

The suffix consists of all characters in the file after (but not including) the last '.'.

Example:

QFileInfo fi("/tmp/archive.tar.gz");
QString ext = fi.suffix();  // ext = "gz"

The suffix of a file is computed equally on all platforms, independent of file naming conventions (e.g., ".bashrc" on Unix has an empty base name, and the suffix is "bashrc").

See also fileName(), completeSuffix(), baseName(), and completeBaseName().

void QFileInfo::swap(QFileInfo &other)

Swaps this file info with other. This function is very fast and never fails.

This function was introduced in Qt 5.0.

QString QFileInfo::symLinkTarget() const

Returns the absolute path to the file or directory a symbolic link points to, or an empty string if the object isn't a symbolic link.

This name may not represent an existing file; it is only a string. QFileInfo::exists() returns true if the symlink points to an existing file.

This function was introduced in Qt 4.2.

See also exists(), isSymLink(), isDir(), and isFile().

bool QFileInfo::operator!=(const QFileInfo &fileinfo) const

Returns true if this QFileInfo object refers to a different file than the one specified by fileinfo; otherwise returns false.

See also operator==().

bool QFileInfo::operator==(const QFileInfo &fileinfo) const

Returns true if this QFileInfo object refers to a file in the same location as fileinfo; otherwise returns false.

Note that the result of comparing two empty QFileInfo objects, containing no file references (file paths that do not exist or are empty), is undefined.

Warning: This will not compare two different symbolic links pointing to the same file.

Warning: Long and short file names that refer to the same file on Windows are treated as if they referred to different files.

See also operator!=().

Related Non-Members

typedef QFileInfoList

Synonym for QList<QFileInfo>.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值