在 Ubuntu(Linux)下使用 C 语言通过 opendir / readdir 获取子目录,核心思路是:
opendir 打开目录readdir 遍历目录项d_type 或 stat 判断是否为目录. 和 ..d_type)#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[]) {
const char *path = "."; // 当前目录
DIR *dir = opendir(path);
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 跳过 . 和 ..
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
// DT_DIR 表示目录
if (entry->d_type == DT_DIR) {
printf("子目录: %s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
stat)d_type 在某些情况下可能返回 DT_UNKNOWN(如某些文件系统),更稳妥的是用 stat:
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main() {
const char *path = ".";
DIR *dir = opendir(path);
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
char fullpath[1024];
struct stat st;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
if (stat(fullpath, &st) == 0 && S_ISDIR(st.st_mode)) {
printf("子目录: %s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
如果你需要递归遍历子目录:
void list_dir(const char *path) {
DIR *dir = opendir(path);
if (!dir) return;
struct dirent *entry;
char fullpath[1024];
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
struct stat st;
if (stat(fullpath, &st) == 0 && S_ISDIR(st.st_mode)) {
printf("目录: %s\n", fullpath);
list_dir(fullpath); // 递归
}
}
closedir(dir);
}
opendir 打开目录readdir 获取子项DT_DIR 或 stat() 判断是否是目录. 和 ..如果你是想用 C++ / Python / Shell 或需要过滤特定目录,可以继续问我。