Linux目录遍历函数

1.打开一个目录

#include <sys/types.h>

#include <dirent.h>

DIR *opendir(const char *name);

参数:

-name:需要打开的目录的名称

返回值:

DIR * 类型,理解为目录流

错误返回NULL

2.读取目录中的数据

#include <dirent.h>

struct dirent *readdir(DIR *dirp);

参数

-dirp是opendir返回的结果

返回值:

struct dirent,代表读取到的文件的信息

读取到了末尾或者失败了返回NULL

3.关闭目录

#include <sys/types.h>

#include <dirent.h>

int closedir(DIR *dirp);

cpp 复制代码
#include <sys/types.h>
#include <dirent.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <errno.h>
int getFileNum(const char* path);
int main(int argc, char * argv[]) {
    if(argc < 2) {
        printf("%s path\n", argv[0]);
        return -1;
    }
    int num = getFileNum(argv[1]);
    printf("普通文件的个数为:%d\n", num);
    return 0;
}
//用于获取目录下所有普通文件的个数
int getFileNum(const char* path) {
    //打开目录
    DIR * dir = opendir(path);
    if(dir == NULL) {
        perror("opendir");
        exit(0);
    }
    struct dirent* ptr;
    //定义变量,记录普通文件的个数
    int total = 0;
    while((ptr = readdir(dir)) != NULL) {
        //获取名称
        char * dname = ptr->d_name;

        //忽略掉.和..
        if(strcmp(dname, ".") == 0 || strcmp(dname, "..") == 0) {
            continue;
        }
        //判断是普通文件还是目录
        if(ptr->d_type == DT_DIR) {
            //目录,需要继续读取这个目录
            char newpath[256];
            sprintf(newpath, "%s/%s", path, dname);
            total += getFileNum(newpath);
        }
        if(ptr->d_type == DT_REG) {
            //普通文件
            total++;
        }
    }
    //关闭目录
    closedir(dir);
    return total;
}
相关推荐
t***54410 分钟前
如何在 Dev-C++ 中设置和使用 Clang 编译器
开发语言·c++
嵌入式×边缘AI:打怪升级日志33 分钟前
从硬编码按键驱动到 Linux Platform 设备树驱动:逐行解剖与融会贯通
linux·运维·服务器
楼田莉子42 分钟前
CMake学习:CMake语法
c++·后端·学习·软件构建
无限进步_1 小时前
C++ 继承机制完全解析:从基础原理到菱形继承问题
java·开发语言·数据结构·c++·vscode·后端·算法
盐焗鹌鹑蛋1 小时前
【C++】vector类
c++
jf加菲猫1 小时前
第15章 文件和目录
开发语言·c++·qt·ui
小周技术驿站1 小时前
Linux 权限管理细节详解
linux·运维·服务器·ubuntu·centos
思麟呀1 小时前
Select多路转接
linux·网络·c++·网络协议·http
aq55356001 小时前
开源吐槽大会:让技术痛点变笑点
c++·mfc
t***5442 小时前
如何在 Dev-C++ 中切换编译器至 Clang
开发语言·c++