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;
}
相关推荐
mzhan0174 分钟前
Linux: compare的直观性
java·linux·服务器
AbandonForce5 分钟前
哈希表(HashTable,散列表)个人理解
开发语言·数据结构·c++·散列表
原来是猿14 分钟前
TCP Server 业务扩展实战:从 Echo 到远程命令执行与词典翻译
linux·运维·服务器
样例过了就是过了27 分钟前
LeetCode热题100 编辑距离
数据结构·c++·算法·leetcode·动态规划
z2005093028 分钟前
C++中位图和布隆过滤器的一些面试题
开发语言·c++
剑神一笑1 小时前
Linux awk 命令:文本处理的瑞士军刀
linux·运维·chrome
khalil10201 小时前
代码随想录算法训练营Day-46 动态规划13 | 647. 回文子串、516.最长回文子序列、动态规划总结
数据结构·c++·算法·leetcode·动态规划·回文子串·回文子序列
挨踢ren1 小时前
单例模式:C++实现与多线程安全
c++·设计模式
用户805533698032 小时前
现代Qt开发教程(新手篇)1.14——日志
c++·qt
用户2367829801682 小时前
Linux df 命令深度解析:从磁盘空间监控到 inode 耗尽排查
linux