1. Qt的API及其说明
首先,Qt有如下函数能够判断路径或者文件是否可写:
bool QFileInfo::isWritable() const
在官方的描述文档中,存在如下的描述:
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.
注意:如果未启用 NTFS 权限检查,Windows 上的结果将仅反映文件是否标记为只读。
同样还能找到如下的信息:
Note: On NTFS file systems, ownership and permissions checking is disabled by default for performance reasons.
注意:在 NTFS 文件系统上,出于性能原因,所有权和权限检查默认是禁用的。
2. 忽略限制的简单测试
查看上面的信息能够了解到,对于NTFS文件系统,仅仅只使用QFileInfo::isWritable()
是不能得到相应的效果的。
例如我系统上存在一个文件夹"C:/Program Files (x86)/Raspberry Pi Imager",这个路径经过测试已经知道普通情况下是不可写的。
使用如下的语句进行测试:
QFileInfo info("C:/Program Files (x86)/Raspberry Pi Imager");
qDebug()<< info.isWritable();
得到的结果如下:
true
明显判断是错误的。也就是这样是不可行的。
3. 打开NTFS限制的文档说明
Qt的文档中有提到如下内容:
Note: On NTFS file systems, ownership and permissions checking is disabled by default for performance reasons. To enable it, include the following line:
注意:在 NTFS 文件系统上,出于性能原因,所有权和权限检查默认是禁用的。 要启用它,请包含以下行:
extern Q_CORE_EXPORT int qt_ntfs_permission_lookup;
Permission checking is then turned on and off by incrementing and decrementing qt_ntfs_permission_lookup by 1.
然后通过将 qt_ntfs_permission_lookup 递增和递减 1 来打开和关闭权限检查。
qt_ntfs_permission_lookup++; // turn checking on
qt_ntfs_permission_lookup--; // turn it off again
4. 正确的代码
为了方便演示,下面简单使用一个简单程序进行说明:
#include <QDebug>
#include <QFileInfo>
extern Q_CORE_EXPORT int qt_ntfs_permission_lookup;
int main(int argc, char *argv[])
{
qt_ntfs_permission_lookup ++;
QFileInfo info("C:/Program Files (x86)/Raspberry Pi Imager");
qDebug() << info.absoluteFilePath();
qDebug() << info.isWritable();
qt_ntfs_permission_lookup --;
return 0;
}
显示的结果如下:
"C:/Program Files (x86)/Raspberry Pi Imager"
false
获得的结果与上面相比是正确的。
再通过其他路径的测试,发现这样的结果才是正确的。