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

运行结果如下:

相关推荐
jinyishu_6 小时前
模拟实现 C++ 栈和队列——从适配器模式看懂 STL 容器之美
java·c++·适配器模式
hehelm6 小时前
AI大模型接入SDK—通用模块设计
linux·开发语言·c++
什巳6 小时前
JAVA练习309- 二叉树的层序遍历
java·数据结构·算法·leetcode
麻瓜老宋8 小时前
AI开发C语言应用按步走,表达式计算器calc的第一步,中缀表达式词法分析
c语言·开发语言·atomcode
hold?fish:palm9 小时前
RDB全量快照备份
c++·redis·后端
什巳9 小时前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode
一个初入编程的小白9 小时前
C语言:函数栈帧与销毁
c语言·开发语言
smj2302_796826529 小时前
解决leetcode第3989题网格中保持一致的最大列数
python·算法·leetcode
盐焗鹌鹑蛋10 小时前
【C++】C++11:列表初始化、声明、STL升级
c++
巧克力男孩dd10 小时前
Python超典型练习题(第一次作业)
开发语言·python·算法