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;
}
相关推荐
极客小张8 分钟前
基于STM32MP157与OpenCV的嵌入式Linux人脸识别系统开发设计流程
linux·stm32·单片机·opencv·物联网
x66ccff13 分钟前
【linux】4张卡,坏了1张,怎么办?
linux·运维·服务器
憧憬成为原神糕手16 分钟前
c++_list
开发语言·c++
zyh2005043018 分钟前
c++的decltype关键字
c++·decltype
jjb_23633 分钟前
LinuxC高级作业2
linux·bash
2401_8628867835 分钟前
蓝禾,汤臣倍健,三七互娱,得物,顺丰,快手,游卡,oppo,康冠科技,途游游戏,埃科光电25秋招内推
前端·c++·python·算法·游戏
OH五星上将42 分钟前
OpenHarmony(鸿蒙南向开发)——小型系统内核(LiteOS-A)【扩展组件】上
linux·嵌入式硬件·harmonyos·openharmony·鸿蒙开发·liteos-a·鸿蒙内核
徐霞客3201 小时前
对于C++继承中子类与父类对象同时定义其析构顺序的探究
开发语言·c++
拾光师1 小时前
linux之网络命令
linux·服务器·网络
敲上瘾1 小时前
多态的使用和原理(c++详解)
开发语言·数据结构·c++·单片机·aigc·多态·模拟