3

我有一些代码可以列出目录中的文件。对于 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总是抛出.File access error: sharing violation: \pagefile.sysC:\

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

4

1 回答 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
}
于 2019-02-12T21:11:19.963 回答