linux

如何用copendir遍历目录树

小樊
47
2025-06-30 04:29:13
栏目: 编程语言

copendir() 函数用于打开一个目录流,以便使用 readdir() 函数读取目录中的条目。要使用 copendir() 遍历目录树,你需要递归地遍历每个子目录。以下是一个简单的示例,展示了如何使用 copendir()readdir() 遍历目录树:

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

void list_directory_contents(const char *path) {
    struct dirent *entry;
    DIR *dp = opendir(path);

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

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

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

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

        if (S_ISDIR(st.st_mode)) {
            printf("Directory: %s\n", full_path);
            list_directory_contents(full_path);
        } else {
            printf("File: %s\n", full_path);
        }
    }

    closedir(dp);
}

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

    list_directory_contents(argv[1]);
    return EXIT_SUCCESS;
}

这个程序接受一个命令行参数,该参数指定要遍历的目录。list_directory_contents() 函数会打开一个目录流,然后使用 readdir() 函数读取目录中的每个条目。对于每个条目,它会检查是否为目录。如果是目录,它会递归地调用 list_directory_contents() 函数。否则,它会打印文件名。

要编译此程序,请将其保存为 traverse_directory_tree.c,然后运行以下命令:

gcc traverse_directory_tree.c -o traverse_directory_tree

现在,你可以使用以下命令运行程序,指定要遍历的目录:

./traverse_directory_tree /path/to/directory

请注意,这个示例仅适用于 POSIX 兼容的系统(如 Linux 和 macOS)。在 Windows 上,你需要使用不同的函数(如 FindFirstFile()FindNextFile())来遍历目录。

0
看了该问题的人还看了