在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
函數的參數更改為相應的目錄路徑即可。