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);
}

运行结果如下:

相关推荐
硕风和炜1 小时前
【LeetCode: 2492. 两个城市间路径的最小分数 + DFS】
java·算法·leetcode·深度优先·dfs·bfs·并查集
upgrador1 小时前
基础知识:C++ STL构造函数的左闭右开惯例及其实现原理
开发语言·c++
我是一颗柠檬2 小时前
【Java项目技术亮点】加权轮询负载均衡算法
java·算法·负载均衡
灯厂码农2 小时前
C语言动态内存分配完全指南(malloc、calloc、realloc、free)
java·c语言·算法
wuyk5552 小时前
24. C 语言模块化:不是拆几个.c 文件那么简单
c语言·开发语言·stm32·单片机
qq_241585613 小时前
可用在中断中浮点数打印类似printf
c语言
凯瑟琳.奥古斯特3 小时前
K次取反最大化数组和解法(力扣1005)
开发语言·c++·算法·leetcode·职场和发展
林中青木3 小时前
CT重构原理及C++代码实现
c++·计算机视觉·重构
满天星83035773 小时前
Protobuf的介绍及使用
c++
☆cwlulu4 小时前
调试排查工具介绍(gdb、strace、Valgrind等)
开发语言·c++·嵌入式硬件·ubuntu