Qt检查路径(目录)或文件(特别是NTFS文件系统)是否可写

14 篇文章 0 订阅

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

获得的结果与上面相比是正确的。
再通过其他路径的测试,发现这样的结果才是正确的。

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值