温馨提示×

ubuntu copendir怎么结合readdir

小樊
37
2026-09-20 22:27:28
栏目: 智能运维

在 Ubuntu(Linux)下,opendir 和 readdir 通常是配对使用的,用来遍历目录中的文件和子目录。它们都来自 <dirent.h>。

下面给你一个清晰的使用流程和示例。


一、基本用法流程

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

DIR *dir = opendir("目录路径");
if (dir == NULL) {
    perror("opendir");
    return -1;
}

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

closedir(dir);

二、完整示例(遍历当前目录)

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

int main() {
    DIR *dir = opendir(".");
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        printf("文件名: %s\n", entry->d_name);
    }

    closedir(dir);
    return 0;
}

编译运行:

gcc test.c -o test
./test

三、常见配合用法

1️⃣ 过滤 . 和 ..

while ((entry = readdir(dir)) != NULL) {
    if (strcmp(entry->d_name, ".") == 0 ||
        strcmp(entry->d_name, "..") == 0)
        continue;

    printf("%s\n", entry->d_name);
}

2️⃣ 判断文件类型(推荐用 stat)

#include <sys/stat.h>

struct stat st;
char path[256];
snprintf(path, sizeof(path), "%s/%s", dirname, entry->d_name);

stat(path, &st);
if (S_ISDIR(st.st_mode)) {
    printf("[目录] %s\n", entry->d_name);
} else {
    printf("[文件] %s\n", entry->d_name);
}

3️⃣ 递归遍历目录(常见面试题)

void list_dir(const char *path) {
    DIR *dir = opendir(path);
    if (!dir) return;

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
            continue;

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

        printf("%s\n", full);

        struct stat st;
        stat(full, &st);
        if (S_ISDIR(st.st_mode))
            list_dir(full);
    }
    closedir(dir);
}

四、常见错误

❌ 忘记 closedir
❌ 直接用 entry->d_type(在某些文件系统上不可靠)
❌ 路径不存在导致 opendir 返回 NULL


五、总结一句话

opendir 打开目录,readdir 逐个读取目录项,closedir 关闭目录

如果你是想做:

  • 递归删除
  • 查找文件
  • 类似 ls -R
  • 多线程遍历

可以继续问我,我可以给你对应示例。

0 踩