如何在目录上迭代并识别或省略NTFS连接(符号链接ish)

How can I iterate over a directory and identify or omit NTFS junctions (symlink-ish)

本文关键字:NTFS 连接 ish 符号链接 识别 迭代      更新时间:2023-10-16

我有一些代码来列出目录中的文件。对于Windows系统,我希望最终能得到一个文件和文件夹列表,与您在Windows资源管理器中看到的内容相匹配。例如,当我在Server 2016上列出C:\时,我希望拥有Users文件夹,而不是Documents and Settings连接。目前我两者都有,没有明显的区分方法。

我当前的代码如下:

boost::filesystem::directory_iterator itr(dir);
boost::filesystem::directory_iterator end;
Poco::SharedPtr<Poco::JSON::Array> fileList(new Poco::JSON::Array);
for (; itr != end; ++itr) {
boost::filesystem::path entryPath = itr->path();
Poco::File file(entryPath.string());
// ...

我尝试了PocoisLink()方法,但对于连接,它返回false。

我还尝试了Poco::DirectoryIterator,它给出了与Boost相同的行为,以及Poco::SortedDirectoryIterator,它在读取C:时总是抛出File access error: sharing violation: pagefile.sys

理想情况下,此代码应包括Linux和MacOS系统上的符号链接,而忽略Windows上的连接。

以下是我最终想到的。这不是一个完美的解决方案——它更像是一个启发式而不是一个合适的标识符——但它似乎对我的用例来说足够好:

#ifdef _WIN32
#include <windows.h>
#endif
bool FileController::isNtfsJunction(const std::string& dirPath) const {
#ifdef _WIN32
DWORD attrs = GetFileAttributesA(dirPath.c_str());
if (INVALID_FILE_ATTRIBUTES == attrs) {
DWORD err = GetLastError();
logger.error("Could not determine if path is NTFS Junction: %s. Error: %s", dirPath, err);
return false;
}
return attrs & FILE_ATTRIBUTE_DIRECTORY &&
attrs & FILE_ATTRIBUTE_REPARSE_POINT &&
attrs & FILE_ATTRIBUTE_HIDDEN &&
attrs & FILE_ATTRIBUTE_SYSTEM;
#else
return false;
#endif
}