考虑以下代码片段
#include <iostream>
#include <windows.h>
int main()
{
WIN32_FILE_ATTRIBUTE_DATA wfad;
GetFileAttributesEx(("C:\\TEMP\\noreadfile"), GetFileExInfoStandard, &wfad); //"noreadfile" is unreadable file
std::cout << wfad.dwFileAttributes; // 128
return 0;
}
对于 Windows 上的不可读文件(没有读取权限的文件或在其属性 -> 安全选项卡中将其读取权限设置为“拒绝”的文件),GetFileAttributesEx
返回 FILE_ATTRIBUTE_NORMAL
,表示no other attribute is set对于那个文件。
对于可写文件和非只读文件,也会返回此属性。
我们使用此信息在我们的产品代码中设置文件的权限。
我们得出结论,在文件不可读的情况下,GetFileAttributesEx
可能会返回不正确的属性。我们想知道我们的结论是否正确。
如果是,那么这是 GetFileAttributesEx
的已知问题吗?
如果不是那么
使用 Windows API 或如果可能使用 Boost 或标准 C++ 文件系统库获取不可读文件的文件属性(也许是文件权限?)的正确方法是什么?
最佳答案
它可能根本不会成功。如果您查看 documentation for GetFileAttributesEx ,它实际上返回一个 BOOL。
Return value If the function succeeds, the return value is a nonzero value.
If the function fails, the return value is zero (0). To get extended error information, call GetLastError.
我的猜测是,如果调用失败,“fwad”是未定义的。尝试检查失败指示的返回值。我的猜测是 GetLastError 将返回类似 ERROR_ACCESS_DENIED 的内容.
Windows API 不会抛出异常,因此很遗憾,您必须检查几乎每个返回值。
关于c++ - Windows 上不可读的文件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48022240/