在 Ubuntu(Linux)下使用 C 语言递归遍历目录,通常会用到 opendir、readdir 和 closedir,并结合 stat 判断是否为子目录。
下面给你一个完整可运行的示例。
opendir():打开目录readdir():读取目录项closedir():关闭目录stat() / lstat():获取文件信息S_ISDIR():判断是否为目录#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
void list_dir(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
char fullpath[1024];
dir = opendir(path);
if (!dir) {
perror("opendir");
return;
}
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, &statbuf) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
printf("目录: %s\n", fullpath);
list_dir(fullpath); // 递归
} else {
printf("文件: %s\n", fullpath);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "用法: %s <目录>\n", argv[0]);
return 1;
}
list_dir(argv[1]);
return 0;
}
gcc recursive_opendir.c -o recursive_opendir
./recursive_opendir /path/to/dir
lstat() + S_ISLNK() 判断perror告诉我你的使用场景即可。