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

运行结果如下:

相关推荐
203号居民10 分钟前
LeetCode hot 100 —560. 和为 K 的子数组
java·算法·leetcode
退休倒计时36 分钟前
【每日一题】LeetCode 20. 有效的括号 TypeScript
算法·leetcode·职场和发展·typescript
文心快码BaiduComate39 分钟前
光本位联合文心快码打造面向光电芯片研发的全栈AI Agent Lightmate
算法
郝学胜-神的一滴40 分钟前
Qt 高级编程 042:进度条从入门到自定义美化
开发语言·c++·qt·软件开发·用户界面
啦啦啦啦啦zzzz1 小时前
5种IO模型
运维·服务器·网络·c++
一次旅行1 小时前
ViT/CLIP/LLaVA/GPT-4V/VideoLLM多模态架构全解:原理仿真+工业落地选型+完整推理代码
人工智能·算法·架构
呱呱巨基1 小时前
Docker 基础概念学习
linux·c++·学习·docker
神明不懂浪漫2 小时前
【第五章】队列
开发语言·数据结构·经验分享·笔记·算法
happy_baymax2 小时前
MATLAB MCP Server+ MATLAB Agentic Toolkit+Simulink Agentic Toolkit自动更新批处理文件.ps1
人工智能·算法
神明不懂浪漫2 小时前
【第六章】二叉树
开发语言·数据结构·经验分享·笔记·算法