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

运行结果如下:

相关推荐
王老师青少年编程4 分钟前
信奥赛C++提高组csp-s之组合数学专题课:卡特兰数
c++·组合数学·卡特兰数·csp·信奥赛·csp-s·提高组
闻道且行之4 分钟前
C/C++ HTTP 服务:常用方法与实现方式全解析
c语言·c++·http·libhv·curl·mongoose·libcurl
Wect8 分钟前
LeetCode 4. 寻找两个正序数组的中位数:二分优化思路详解
前端·算法·typescript
ZPC821011 分钟前
moveitcpp 没办法执行的问题
人工智能·pytorch·算法·机器人
YJlio12 分钟前
《Windows 11 从入门到精通》读书笔记 1.4.9:全新的微软应用商店——“库 + 多设备同步”把它从鸡肋变成刚需入口
c语言·网络·python·数码相机·microsoft·ios·iphone
智者知已应修善业14 分钟前
【C++非递归剪枝问题凑钱方案数】2024-7-18
c语言·c++·经验分享·笔记·算法·剪枝
BigLeo14 分钟前
c++中,声明(Declaration)与定义(Definition)有什么不同?
c++
YJlio15 分钟前
《Windows 11 从入门到精通》读书笔记 1.4.10:集成的微软 Teams——办公与社交的无缝衔接
c语言·网络·python·数码相机·ios·django·iphone
星辰徐哥16 分钟前
C语言Web开发:CGI、FastCGI、Nginx深度解析
c语言·前端·nginx
Yolo_TvT16 分钟前
C++:缺省参数
开发语言·c++·算法