温馨提示×

如何递归用ubuntu copendir

小樊
46
2026-09-14 18:54:36
栏目: 智能运维

在 Ubuntu(Linux)下使用 C 语言递归遍历目录,通常会用到 opendirreaddirclosedir,并结合 stat 判断是否为子目录。

下面给你一个完整可运行的示例


一、核心函数说明

  • opendir():打开目录
  • readdir():读取目录项
  • closedir():关闭目录
  • stat() / lstat():获取文件信息
  • S_ISDIR():判断是否为目录

二、递归遍历目录示例(C 语言)

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

void list_dir(const char *path) {
    DIR *dir;
    struct dirent *entry;
    struct stat statbuf;
    char fullpath[1024];

    dir = opendir(path);
    if (!dir) {
        perror("opendir");
        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, &statbuf) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(statbuf.st_mode)) {
            printf("目录: %s\n", fullpath);
            list_dir(fullpath);  // 递归
        } else {
            printf("文件: %s\n", fullpath);
        }
    }

    closedir(dir);
}

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

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

三、编译 & 运行

gcc recursive_opendir.c -o recursive_opendir
./recursive_opendir /path/to/dir

四、注意事项

  1. 不要遍历符号链接目录(避免死循环)
    可用 lstat() + S_ISLNK() 判断
  2. 路径长度要足够(示例用 1024)
  3. 权限不足时会 perror

五、如果你想要

  • ✅ 只统计文件数量
  • ✅ 排除某些目录
  • ✅ 多线程遍历
  • ✅ C++ / Python 版本

告诉我你的使用场景即可。

0