温馨提示×

centos readdir怎么获取

小樊
45
2026-09-30 07:20:22
栏目: 智能运维

在 CentOS(Linux) 下,readdir 是 C 语言 POSIX API,用于读取目录内容。下面从「系统调用」和「示例代码」两个层面说明。


一、readdir 是什么

readdir 属于 <dirent.h>,用于遍历目录中的文件/子目录。

函数原型:

#include <dirent.h>

struct dirent *readdir(DIR *dirp);
  • DIR *:由 opendir() 返回
  • 返回值:struct dirent *
  • 读到结尾返回 NULL

二、基本使用步骤

  1. opendir() 打开目录
  2. readdir() 循环读取
  3. closedir() 关闭目录

三、完整示例(CentOS / Linux 通用)

示例代码 readdir_test.c

#include <stdio.h>
#include <dirent.h>

int main(int argc, char *argv[])
{
    DIR *dir;
    struct dirent *entry;

    if (argc < 2) {
        printf("Usage: %s <dir>\n", argv[0]);
        return 1;
    }

    dir = opendir(argv[1]);
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

    while ((entry = readdir(dir)) != NULL) {
        printf("%s\n", entry->d_name);
    }

    closedir(dir);
    return 0;
}

四、编译和运行

gcc readdir_test.c -o readdir_test
./readdir_test /etc

五、struct dirent 常用字段

struct dirent {
    ino_t          d_ino;     // inode 号
    off_t          d_off;
    unsigned short d_reclen;
    unsigned char  d_type;    // 文件类型
    char           d_name[];  // 文件名
};

判断文件类型(d_type)

if (entry->d_type == DT_REG)  // 普通文件
if (entry->d_type == DT_DIR)  // 目录

六、常见注意点(CentOS 特有)

  1. . 和 .. 也会读到
  2. 需要包含:
    #include <dirent.h>
    #include <sys/types.h>
    
  3. 如果目录很大,推荐用 readdir_r(线程安全,老接口)或 readdir(glibc 已线程安全)

七、进阶:递归遍历目录(可选)

如果你需要:

  • 递归读取子目录
  • 获取文件大小 / 权限

可以告诉我,我可以给你 递归版 readdir + stat 示例。


如果你的问题是:

  • Python 怎么 readdir
  • Shell 怎么等价实现
  • CentOS 7 / 8 差异

也可以继续问我。

0 踩