温馨提示×

怎样遍历ubuntu copendir

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

在 Ubuntu(Linux)下,如果你说的是 用 C/C++ 遍历目录(opendir / readdir),下面给你一个完整、常用的示例。


一、基本思路

使用 POSIX 标准目录函数:

  • opendir():打开目录
  • readdir():读取目录项
  • closedir():关闭目录

需要头文件:

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

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

#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 listdir.c -o listdir
./listdir

三、遍历指定目录

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

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

    DIR *dir = opendir(argv[1]);
    if (!dir) {
        perror("opendir");
        return 1;
    }

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

    closedir(dir);
    return 0;
}

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

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

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

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

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

        struct stat st;
        stat(full, &st);

        if (S_ISDIR(st.st_mode)) {
            printf("[DIR] %s\n", full);
            list_dir(full);
        } else {
            printf("[FILE] %s\n", full);
        }
    }
    closedir(dir);
}

int main(int argc, char *argv[]) {
    const char *path = argc > 1 ? argv[1] : ".";
    list_dir(path);
    return 0;
}

五、常见注意点

  • readdir() 会返回 ...
  • 文件名在 d_name
  • 判断文件类型要用 stat()
  • 多线程中 readdir() 不是线程安全的,可用 readdir_r()

如果你说的是:

  • shell 遍历目录
  • Python 遍历目录
  • C++ filesystem 遍历
  • 过滤某种文件

可以告诉我,我可以直接给你对应版本。

0