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

C++目录文件存入List异常:仅获父路径未取文件名的修复方法

问题修复:将文件完整路径存入list而非父目录路径

你遇到的问题核心很直观——遍历目录时,你把**父目录路径path**重复塞进了list,而非遍历到的单个文件的完整路径,这才导致最终list里全是父目录的地址。

错误原因拆解

看这段循环代码就能发现问题:

for (const auto& entry : fs::directory_iterator(path)) {
    std::cout << entry.path() << std::endl;
    pages.push_back(path); // 这里错把父目录path加进list了!
}

你在cout里明明正确输出了entry.path()(文件的完整路径),但往list存的时候却用了定义好的父目录字符串path,自然存的全是同一个父目录路径。

修复后的完整代码

只需要把pages.push_back(path)改成pages.push_back(entry.path().string())就行——因为entry.path()返回的是fs::path类型,得转成string才能存入list<string>:

#include <iostream>
#include<vector>
#include<list>
#include<map>
#include<queue>
#include<fstream>
#include<string>
#include <filesystem>
namespace fs = std::filesystem;
using namespace std;

string path = "C:/Users/deonh/Downloads/intranets/intranet1"; //该路径指向包含所有待处理文件的目录
string path5 = "C:/Users/deonh/Downloads/intranets/intranet5";
string path7 = "C:/Users/deonh/Downloads/intranets/intranet7";

int main() {
    list<string>pages;
    map<string, int> page;
    //打印文件以验证遍历逻辑正常
    for (const auto& entry : fs::directory_iterator(path)) {
        std::cout << entry.path() << std::endl;
        // 修复:将entry的完整路径转成string存入list
        pages.push_back(entry.path().string());
    }
    for (list<string> ::iterator it = pages.begin(); it != pages.end(); it++) {
        cout << *it << endl;
    }
    return 0;
}

额外补充说明

  • fs::directory_iterator遍历得到的entry是fs::directory_entry类型,entry.path()会返回该文件/目录的完整fs::path对象;
  • 调用.string()方法可以把fs::path转换成标准的std::string,完美适配list<string>的存储要求;
  • 这段代码需要C20及以上版本支持,因为std::filesystem是C20纳入的标准库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:07:15