在C语言中,opendir
函数用于打开一个目录流,以便读取目录中的文件和子目录。以下是一个简单的示例,展示如何使用opendir
、readdir
和closedir
函数来读取一个目录及其子目录中的所有条目:
#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;
}
opendir
函数打开指定路径的目录。如果目录打开失败,opendir
返回NULL
,并设置errno
。readdir
函数读取目录中的每个条目。readdir
返回一个指向dirent
结构的指针,该结构包含条目的信息。.
和..
是当前目录和父目录的特殊条目,通常不需要处理。printf
函数打印条目的名称。d_type
字段),则递归调用list_directory_contents
函数来处理该子目录。closedir
函数关闭目录流。这个示例程序会列出指定目录及其所有子目录中的文件和子目录。你可以根据需要修改路径和输出格式。