linux

copendir如何遍历目录结构

小樊
43
2025-03-25 07:17:11
栏目: 编程语言

copendir 函数用于打开一个目录流,以便后续使用 readdir 函数读取目录中的条目。要遍历目录结构,你需要递归地处理子目录。以下是一个示例代码,展示了如何使用 copendirreaddir 遍历目录结构:

#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 statbuf;
        if (stat(full_path, &statbuf) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(statbuf.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;
}

代码说明:

  1. 打开目录:使用 opendir 打开指定路径的目录。
  2. 读取目录条目:使用 readdir 读取目录中的每个条目。
  3. 跳过特殊条目:跳过当前目录(.)和父目录(..)。
  4. 构建完整路径:使用 snprintf 构建条目的完整路径。
  5. 检查文件类型:使用 stat 获取文件信息,并检查是否为目录。
  6. 递归处理子目录:如果是目录,则递归调用 list_directory_contents 处理子目录。
  7. 关闭目录:使用 closedir 关闭目录流。

使用方法:

编译并运行程序,传入要遍历的目录路径作为参数:

gcc -o listdir listdir.c
./listdir /path/to/directory

这个程序会递归地遍历指定目录及其所有子目录,并打印出每个文件和目录的完整路径。

0
看了该问题的人还看了