You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

fs::recursive_directory_iterator未遍历符号链接下子目录问题求解

解决recursive_directory_iterator不遍历符号链接子目录的问题

默认情况下,std::filesystem::recursive_directory_iterator不会跟随符号链接指向的目录,这是为了避免循环引用(比如符号链接指向父目录)导致的无限遍历风险。要让迭代器遍历符号链接下的子目录,只需在创建迭代器时指定directory_options::follow_directory_symlink选项。

修改后的代码示例:

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

void ScanMediaFolders()
{
    fs::path root_path = "D:\\Projects\\Media";
    // 传入follow_directory_symlink选项,让迭代器跟随符号链接目录
    for (const fs::directory_entry& dir_entry :
         fs::recursive_directory_iterator(root_path, fs::directory_options::follow_directory_symlink)){
        std::cout << dir_entry << '\n';
    }
}

int main() {
    ScanMediaFolders();
    return 0;
}

注意事项

  • 需警惕循环符号链接:如果符号链接形成闭环(如A链接到B,B链接到A),会触发无限递归遍历。可以额外添加directory_options::skip_permission_denied跳过无权限目录,或者在遍历过程中维护已访问路径集合,检测并跳过重复路径。
  • 该功能依赖C++17及以上标准,请确保编译器支持并启用对应标准(比如编译时添加-std=c++17或更高版本参数)。

内容的提问来源于stack exchange,提问作者ObliteratedJillo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 02:12:37