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

运行结果如下:

相关推荐
Hello娃的1 天前
【神经网络】反向传播BP算法
人工智能·神经网络·算法
ZouZou老师1 天前
C++设计模式之责任链模式:以家具生产为例
c++·设计模式·责任链模式
yuyousheng1 天前
CMake详解
c语言
lynnlovemin1 天前
从暴力到高效:C++ 算法优化实战 —— 排序与双指针篇
java·c++·算法
jinxinyuuuus1 天前
快手在线去水印:短链解析、API逆向与视频流的元数据重构
前端·人工智能·算法·重构
Flash.kkl1 天前
优先算法专题十五——BFS_FloodFill
算法·宽度优先
高洁011 天前
向量数据库拥抱大模型
python·深度学习·算法·机器学习·transformer
慕容青峰1 天前
牛客小白月赛 103 C 题题解
c++·算法·sublime text
小龙报1 天前
【算法通关指南:算法基础篇(四)】二维差分专题:1.【模板】差分 2.地毯
c语言·数据结构·c++·深度学习·神经网络·算法·自然语言处理
立志成为大牛的小牛1 天前
数据结构——五十八、希尔排序(Shell Sort)(王道408)
数据结构·学习·程序人生·考研·算法·排序算法