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;
}
相关推荐
散峰而望11 小时前
【基础算法】穷举的艺术:在可能性森林中寻找答案
开发语言·数据结构·c++·算法·随机森林·github·动态规划
那年我七岁11 小时前
android ndk c++ 绘制图片方式
android·c++·python
散峰而望11 小时前
【基础算法】算法的“预谋”:前缀和如何改变游戏规则
开发语言·数据结构·c++·算法·github·动态规划·推荐算法
仰泳的熊猫11 小时前
题目1432:蓝桥杯2013年第四届真题-剪格子
数据结构·c++·算法·蓝桥杯·深度优先·图论
冉佳驹11 小时前
Linux ——— 磁盘存储原理与文件系统工作机制
linux·磁盘·硬链接·inode·软链接·磁盘线性化·目录的本质
BUG_MeDe11 小时前
LINUX MTU/MSS(1500 1460等)的一些理解
linux·运维·服务器
风流倜傥唐伯虎11 小时前
Windows 版 Docker 的 Linux 环境(docker-desktop)与 builder-jammy-base:latest 镜像核心区别
linux·docker·容器
闻缺陷则喜何志丹11 小时前
【数论 快速指数幂 龟速乘】P8652 [蓝桥杯 2017 国 C] 小数第 n 位|普及+
c++·蓝桥杯·数论·快速指数幂·龟速乘
༾冬瓜大侠༿11 小时前
C++string
c语言·开发语言·c++·算法
A懿轩A11 小时前
【Maven 构建工具】Maven 依赖管理详解:坐标、传递、作用域与依赖冲突解决(一篇搞懂)
java·linux·maven