如何迭代目录并识别或省略NTFS结点(symlink-ish)

问题描述 投票:3回答:1

我有一些代码列出目录中的文件。对于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());
    // ...

我尝试了Poco isLink()方法,但它为结点返回false。

我也尝试过Poco::DirectoryIterator,它提供与Boost相同的行为,以及Poco::SortedDirectoryIterator,在阅读File access error: sharing violation: \pagefile.sys时总是抛出C:\

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

c++ boost ntfs poco-libraries junction
1个回答
0
投票

这是我最终提出的。它不是一个完美的解决方案 - 它更像是一个启发式而不是一个正确的标识符 - 但它似乎对我的用例运行良好:

#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
}
© www.soinside.com 2019 - 2024. All rights reserved.