温馨提示×

debian copendir如何遍历

小樊
38
2026-08-22 21:03:51
栏目: 智能运维

在 Debian(或任何 Linux 系统)中,使用 C 语言 遍历目录,常用的是 opendir() / readdir() 接口。下面给你一个完整、实用的示例,并解释关键点。


一、基本流程(opendir 遍历目录)

  1. opendir() 打开目录
  2. readdir() 读取目录项
  3. closedir() 关闭目录
  4. 判断文件类型(普通文件 / 目录)

二、最简单的示例(遍历当前目录)

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

int main() {
    DIR *dir;
    struct dirent *entry;

    dir = opendir(".");  // 打开当前目录
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

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

    closedir(dir);
    return 0;
}

三、区分文件和目录(常见需求)

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>

int main() {
    DIR *dir;
    struct dirent *entry;
    struct stat st;
    char path[512];

    dir = opendir(".");
    if (!dir) {
        perror("opendir");
        return 1;
    }

    while ((entry = readdir(dir)) != NULL) {
        snprintf(path, sizeof(path), "./%s", entry->d_name);

        if (stat(path, &st) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(st.st_mode)) {
            printf("[DIR]  %s\n", entry->d_name);
        } else {
            printf("[FILE] %s\n", entry->d_name);
        }
    }

    closedir(dir);
    return 0;
}

四、递归遍历目录(遍历子目录)

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>

void list_dir(const char *path) {
    DIR *dir = opendir(path);
    struct dirent *entry;
    char fullpath[512];
    struct stat st;

    if (!dir) return;

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

        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

        if (stat(fullpath, &st) == -1)
            continue;

        if (S_ISDIR(st.st_mode)) {
            printf("[DIR] %s\n", fullpath);
            list_dir(fullpath);  // 递归
        } else {
            printf("[FILE] %s\n", fullpath);
        }
    }

    closedir(dir);
}

int main() {
    list_dir(".");
    return 0;
}

五、常见注意点

1. ...

  • . 表示当前目录
  • .. 表示上级目录
    ✅ 递归时一定要跳过,否则死循环

2. readdir() 返回的是 struct dirent

struct dirent {
    ino_t d_ino;
    off_t d_off;
    unsigned short d_reclen;
    unsigned char d_type; // 不一定可靠
    char d_name[256];
};

⚠️ d_type 在某些文件系统上不可靠,推荐用 stat()


六、编译方式(Debian)

gcc dir.c -o dir
./dir

七、替代方案(如果你愿意)

方法 说明
opendir/readdir 最常用、POSIX
nftw() 高级目录遍历
glob() 通配符遍历
find 命令行工具

如果你需要:

  • 只遍历一层
  • 过滤特定后缀(如 .c
  • 统计文件数量
  • 用 C++ 实现

可以直接告诉我,我可以按你的需求写。

0