温馨提示×

ubuntu copendir如何结合readdir

小樊
41
2026-09-05 18:14:17
栏目: 智能运维

在 Ubuntu(Linux)下,使用 C 语言进行目录操作时,opendirreaddir 通常是成对使用的:

  • opendir:打开一个目录,返回 DIR *
  • readdir:从 DIR * 中逐个读取目录项(struct dirent

下面给你一个完整、常见用法示例,并解释关键点。


一、基本用法示例

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

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

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <directory>\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;
}

二、opendir + readdir 工作流程

opendir()
   ↓
DIR *
   ↓
readdir()  ← 循环调用
   ↓
struct dirent *
   ↓
closedir()

三、关键结构体说明

struct dirent {
    ino_t          d_ino;     // inode 号
    off_t          d_off;     // 偏移
    unsigned short d_reclen;  // 记录长度
    unsigned char  d_type;    // 文件类型
    char           d_name[256]; // 文件名
};

常见 d_type 值

DT_REG  普通文件
DT_DIR  目录
DT_LNK  符号链接

示例:只列出目录

if (entry->d_type == DT_DIR) {
    printf("DIR: %s\n", entry->d_name);
}

四、常见组合技巧

1️⃣ 跳过 ...

if (strcmp(entry->d_name, ".") == 0 ||
    strcmp(entry->d_name, "..") == 0)
    continue;

2️⃣ 递归遍历目录(结合 stat)

#include <sys/stat.h>

char path[512];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);

struct stat st;
stat(path, &st);
if (S_ISDIR(st.st_mode)) {
    // 递归处理
}

3️⃣ 读取失败判断

if (readdir(dir) == NULL && errno != 0) {
    perror("readdir");
}

五、编译方式(Ubuntu)

gcc dir_list.c -o dir_list
./dir_list /tmp

六、总结一句话

opendir 打开目录,readdir 循环读取,closedir 关闭目录

如果你需要:

  • 递归目录遍历
  • 按文件类型过滤
  • readdir_r(线程安全)
  • 或用 C++ / Python 替代

可以直接告诉我。

0