linux

如何使用opendir读取子目录

小樊
59
2025-04-30 11:38:07
栏目: 编程语言

在C语言中,opendir函数用于打开一个目录流,以便读取目录中的文件和子目录。以下是一个简单的示例,展示如何使用opendirreaddirclosedir函数来读取一个目录及其子目录中的所有条目:

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

void list_directory_contents(const char *path) {
    DIR *dir;
    struct dirent *entry;

    // 打开目录
    dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

    // 读取目录中的条目
    while ((entry = readdir(dir)) != NULL) {
        // 跳过当前目录和父目录的特殊条目
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 打印条目的名称
        printf("%s\n", entry->d_name);

        // 如果条目是一个目录,递归调用函数
        char full_path[1024];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
        if (entry->d_type == DT_DIR) {
            list_directory_contents(full_path);
        }
    }

    // 关闭目录
    closedir(dir);
}

int main() {
    const char *path = "."; // 当前目录
    list_directory_contents(path);
    return 0;
}

解释

  1. 打开目录:使用opendir函数打开指定路径的目录。如果目录打开失败,opendir返回NULL,并设置errno
  2. 读取目录条目:使用readdir函数读取目录中的每个条目。readdir返回一个指向dirent结构的指针,该结构包含条目的信息。
  3. 跳过特殊条目...是当前目录和父目录的特殊条目,通常不需要处理。
  4. 打印条目名称:使用printf函数打印条目的名称。
  5. 递归处理子目录:如果条目是一个目录(通过检查d_type字段),则递归调用list_directory_contents函数来处理该子目录。
  6. 关闭目录:使用closedir函数关闭目录流。

注意事项

这个示例程序会列出指定目录及其所有子目录中的文件和子目录。你可以根据需要修改路径和输出格式。

0
看了该问题的人还看了