在C语言中,opendir
函数用于打开一个目录流,以便你可以使用readdir
函数读取目录中的条目。要获取目录下的子目录,你需要遍历目录中的每个条目,并检查它们是否是目录。以下是一个简单的示例,展示了如何使用opendir
和readdir
来获取目录下的所有子目录:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
// 打开目录
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
// 遍历目录中的每个条目
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录(".")和父目录("..")
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 构建完整的路径名
char path[PATH_MAX];
snprintf(path, sizeof(path), "./%s", entry->d_name);
// 获取文件状态
if (stat(path, &statbuf) == -1) {
perror("stat");
continue;
}
// 检查是否是目录
if (S_ISDIR(statbuf.st_mode)) {
printf("子目录: %s\n", entry->d_name);
}
}
// 关闭目录流
closedir(dir);
return EXIT_SUCCESS;
}
在这个示例中,我们首先使用opendir
打开当前目录(.
)。然后,我们使用readdir
遍历目录中的每个条目。对于每个条目,我们使用stat
函数获取其状态信息,并检查它是否是一个目录(通过S_ISDIR
宏)。如果是目录,我们就打印出它的名字。
请注意,这个程序会列出当前目录下的所有子目录,包括隐藏目录(以.
开头的目录)。如果你想要列出其他目录下的子目录,只需将opendir
函数的参数更改为相应的目录路径即可。