温馨提示×

ubuntu copendir如何遍历

小樊
51
2026-10-26 04:13:53
栏目: 智能运维

在 Ubuntu(Linux)下使用 C 语言遍历目录,通常是用 opendir、readdir 和 closedir 这几个函数,而不是“copendir”(可能是笔误)。

下面给你一个完整示例,演示如何用 opendir 遍历目录。


一、基本函数说明

#include <dirent.h>

DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);
  • opendir:打开目录
  • readdir:读取目录项(循环调用)
  • closedir:关闭目录

二、简单目录遍历示例

示例:列出当前目录下所有文件/子目录

#include <stdio.h>
#include <dirent.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;
}

编译运行:

gcc list_dir.c -o list_dir
./list_dir

三、递归遍历目录(常见需求)

如果你要递归遍历子目录,可以配合 stat 判断是否为目录。

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

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

    dir = opendir(path);
    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);

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

        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. d_type 判断目录(不一定可靠)

if (entry->d_type == DT_DIR)

在部分文件系统上 d_type 可能不可用,推荐用 stat。


五、相关命令(非 C)

如果你是想要命令行遍历:

ls -R
find .

如果你说的 “copendir” 是指某个特定库(比如 pthread、并发目录遍历),可以告诉我,我给你更针对性的示例。

0 踩