温馨提示×

使用copendir实现目录树遍历

小樊
37
2025-11-03 05:55:04
栏目: 编程语言

copendir() 是一个用于打开目录的函数,它返回一个指向 DIR 结构的指针,该结构包含有关目录的信息。要使用 copendir() 实现目录树遍历,你需要结合其他函数,如 readdir()closedir()。以下是一个简单的示例,展示了如何使用这些函数遍历目录树:

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

void list_directory_contents(const char *path) {
    DIR *dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != 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 path_stat;
        if (stat(full_path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

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

    closedir(dir);
}

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() 函数递归地遍历目录树,并打印出每个文件和子目录的路径。注意,这个示例没有处理符号链接和其他特殊文件类型。在实际应用中,你可能需要根据需求进行调整。

0