Linux系统编程17-opendir,readdir与closedir.md

#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
    作用: 打开一个目录
    参数:
        - name: 需要打开的目录流
    返回值:
        DIR* 类型, 目录流
        NULL 错误

#include <dirent.h>
struct dirent *readdir(DIR *dirp);
    作用: 读取目录中数据
    参数:
        - dirp opendir 返回的结果
    返回值:
        struct dirent, 代表读取到的文件信息
        NULL, 读取到末尾或失败

        struct dirent
        {
            // 此目录进入点的inode
            ino_t d_ino;
            // 目录文件开头至此目录进入点的位移
            off_t d_off;
            // d_name 的长度, 不包含NULL字符
            unsigned short int d_reclen;
            // d_name 所指的文件类型
            unsigned char d_type;
            // 文件名
            char d_name[256];
        };

        d_type:
            DT_BLK - 块设备
            DT_CHR - 字符设备
            DT_DIR - 目录
            DT_LNK - 软连接
            DT_FIFO - 管道
            DT_REG - 普通文件
            DT_SOCK - 套接字
            DT_UNKNOWN - 未知

#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);
    作用: 关闭目录
    参数:
        - dirp opendir的返回值

实例:读取某个目录下所有普通文件的个数

readFileNum.c

#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int getFileNum(const char *path);

//读取某个目录下所有普通文件的个数
//格式: ./a.out dir
int main(int argc, char const *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 err");
        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;
}

posted @ 2022-10-14 22:14  言叶以上  阅读(43)  评论(0编辑  收藏  举报