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

在C++中获取指定文件名的完整路径(不使用boost::filesystem)

在C++中搜索C盘内同名文件(不使用boost::filesystem)

要在C++里实现C盘内同名文件的搜索,直接调用Windows原生API就能搞定,不用依赖第三方库。核心思路是递归遍历C盘所有目录,用Win32的文件搜索接口逐个检查文件名称,匹配则输出完整路径。

完整实现代码

#include <iostream>
#include <string>
#include <Windows.h>

// 递归搜索目录下的目标文件
void SearchFiles(const std::string& currentDir, const std::string& targetFileName) {
    std::string searchPath = currentDir + "\\*";
    WIN32_FIND_DATA findData;
    HANDLE hFind = FindFirstFileA(searchPath.c_str(), &findData);

    // 处理目录访问失败的情况(比如权限不足)
    if (hFind == INVALID_HANDLE_VALUE) {
        return;
    }

    do {
        // 跳过当前目录"."和上级目录".."
        if (strcmp(findData.cFileName, ".") == 0 || strcmp(findData.cFileName, "..") == 0) {
            continue;
        }

        // 拼接当前项的完整路径
        std::string fullPath = currentDir + "\\" + findData.cFileName;

        // 判断当前项是目录还是文件
        if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
            // 递归搜索子目录
            SearchFiles(fullPath, targetFileName);
        } else {
            // 比对文件名,匹配则输出完整路径
            if (strcmp(findData.cFileName, targetFileName.c_str()) == 0) {
                std::cout << "找到文件:" << fullPath << std::endl;
            }
        }
    } while (FindNextFileA(hFind, &findData) != 0);

    // 关闭搜索句柄
    FindClose(hFind);
}

int main() {
    std::string targetFile = "sample.txt";
    // 从C盘根目录开始搜索
    SearchFiles("C:\\", targetFile);
    return 0;
}

关键细节说明

  • Win32 API依赖:用到FindFirstFileA和FindNextFileA来遍历目录内容,WIN32_FIND_DATA结构体存储文件/目录的信息,这些都是Windows系统自带的接口,无需额外库。
  • 递归遍历:遇到子目录时递归调用搜索函数,确保覆盖C盘所有层级的目录。
  • 权限处理:如果遇到无法访问的目录(比如系统保护目录),FindFirstFileA会返回INVALID_HANDLE_VALUE,直接跳过即可避免程序崩溃。
  • 文件名比对:用strcmp直接比对findData.cFileName和目标文件名,注意区分大小写(如果需要忽略大小写,可以改用_stricmp)。

注意事项

  • 运行程序时可能需要管理员权限,否则部分系统目录无法访问,会漏掉这些目录下的文件。
  • 搜索C盘整个磁盘耗时较长,实际使用中可以考虑限制搜索范围,或者加入进度提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:25:24