c语言遍历文件夹中的文件

文件目录如下,文件夹里还有一些txt文件未展示出来。

使用递归实现,深度优先遍历文件夹中的文件。

代码如下,用了一点C++的语法。

cpp 复制代码
#include <io.h>
#include <iostream>  
using namespace std;

#define MAX_PATH_LENGTH 100

int Traverse(char dir[]);

int main()
{
    char dir[MAX_PATH_LENGTH] = "e:\\test\\*.*";

    Traverse(dir);

    return 0;
}

int Traverse(char dir[])
{
    intptr_t handle;
    _finddata_t findData;

    handle = _findfirst(dir, &findData);
    if (handle == -1)
    {
        cout << "no file exsit\n";
        return -1;
    }

    do
    {
        if ((findData.attrib & _A_SUBDIR) && (strcmp(findData.name, ".") != 0) && (strcmp(findData.name, "..") != 0))
        {
            //it is a directory
            cout << "subdir:" << findData.name << endl;
            char sub_dir[MAX_PATH_LENGTH] = { 0 };
            string s(dir);
            sprintf_s(sub_dir, "%s%s\\*.*", s.substr(0, s.length() - 3).c_str(), findData.name);
            Traverse(sub_dir);
        }
        else if (strcmp(findData.name, ".") == 0 || strcmp(findData.name, "..") == 0)
        {
            //it is . or .. , do nothing
        }
        else
        {
            //it is a file
            cout << "file:" << findData.name << endl;
        }
    } while (_findnext(handle, &findData) == 0);

    _findclose(handle);
}

运行结果如下:

相关推荐
JieE21213 小时前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE21213 小时前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术18 小时前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦19 小时前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
clint45621 小时前
C++进阶(1)——前景提要
c++
用户497863050731 天前
(一)小红的数组操作
算法·编程语言
夜悊1 天前
C++代码示例:进制数简单生成工具
c++
怕浪猫1 天前
Electron 系列文章封面图
算法·架构·前端框架
郝学胜_神的一滴1 天前
CMake 021: IF 条件判据详诠
c++·cmake