温馨提示×

debian copendir怎么写代码

小樊
39
2026-09-07 02:11:18
栏目: 智能运维

在 Debian(或者任意 Linux 系统)下使用 C 语言遍历目录,核心是使用 opendir / readdir / closedir 这套 POSIX 接口。

下面给你一个完整可编译的示例,以及关键点说明。


一、基本示例(递归遍历目录)

示例代码:listdir.c

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

void list_dir(const char *path) {
    DIR *dir;
    struct dirent *entry;

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

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

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

        // 如果是目录,递归进入(可选)
        char fullpath[1024];
        struct stat st;
        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

        if (stat(fullpath, &st) == 0 && S_ISDIR(st.st_mode)) {
            list_dir(fullpath);
        }
    }

    closedir(dir);
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
        return 1;
    }

    list_dir(argv[1]);
    return 0;
}

二、编译方式(Debian)

gcc listdir.c -o listdir

运行:

./listdir /etc

三、关键函数说明

1️⃣ opendir

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

2️⃣ readdir

struct dirent *readdir(DIR *dirp);

常用成员:

entry->d_name   // 文件名
entry->d_type   // 类型(DT_DIR / DT_REG)

3️⃣ closedir

int closedir(DIR *dirp);

四、注意事项(Debian / Linux)

✅ 需要头文件:

#include <dirent.h>

✅ 判断文件类型推荐用 stat(更可靠)

d_type 在某些文件系统(如某些 NFS)可能不可用


五、只列出普通文件(不加递归)

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

如果你需要:

  • ✅ 按文件大小 / 时间排序
  • ✅ 用 C++(std::filesystem
  • ✅ 只遍历一层
  • ✅ 多线程遍历

可以直接告诉我你的使用场景。

0