温馨提示×

debian readdir怎么遍历目录

小樊
53
2026-07-13 19:02:29
栏目: 智能运维

在 Debian(以及大多数 Linux 系统)里,遍历目录通常是通过 opendir / readdir / closedir 这组系统调用完成的,属于 POSIX 标准 API,C 语言里最常用。

下面给你一个完整、常见的用法示例,以及常见注意点。


一、使用 readdir 遍历目录(C 语言)

示例代码

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

int main(int argc, char *argv[])
{
    const char *path = ".";  // 要遍历的目录
    DIR *dir;
    struct dirent *entry;

    dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

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

    closedir(dir);
    return 0;
}

二、编译与运行(Debian)

gcc readdir_example.c -o readdir_example
./readdir_example

三、关键函数说明

1️⃣ opendir

DIR *opendir(const char *name);
  • 打开目录
  • 成功返回 DIR*
  • 失败返回 NULL

2️⃣ readdir

struct dirent *readdir(DIR *dirp);
  • 每次调用返回下一个目录项
  • 返回 NULL 表示结束或出错

struct dirent 常用字段:

char d_name[256];   // 文件名
ino_t d_ino;        // inode 号

3️⃣ closedir

int closedir(DIR *dirp);

四、过滤 ...

readdir 会返回 ...,通常需要过滤:

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

五、递归遍历目录(进阶)

如果你想递归遍历子目录,通常会结合 stat 判断是否是目录:

#include <sys/stat.h>

struct stat st;
stat(entry->d_name, &st);

if (S_ISDIR(st.st_mode)) {
    // 是目录,递归处理
}

⚠️ 注意:递归时要处理路径拼接,避免死循环(如符号链接)


六、其他方式(补充)

1️⃣ scandir(更方便)

struct dirent **namelist;
int n = scandir(".", &namelist, NULL, alphasort);

2️⃣ Shell 遍历

for f in *; do
    echo "$f"
done

七、常见错误

❌ 忘记 closedir
❌ 把 readdir 当文件内容读取(它只读目录项)
❌ 未处理 ...


如果你需要:

  • 递归遍历
  • 只遍历普通文件
  • 用 C++ / Python / Shell
  • 处理符号链接

告诉我你的具体需求,我可以直接给你对应的代码。

0