在 Ubuntu(Linux)下,opendir / readdir / closedir 是 C 语言标准库(<dirent.h>)中用来遍历目录的接口。下面给你一个完整可用的示例,并解释每一步。
opendir(path):打开目录,返回 DIR*readdir(dir):逐个读取目录项,返回 struct dirent*closedir(dir):关闭目录stat() 判断是文件还是目录,实现递归遍历list_dir.c#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[]) {
const char *path = argc > 1 ? argv[1] : ".";
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
gcc list_dir.c -o list_dir
./list_dir /path/to/dir
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
void list_dir(const char *path) {
DIR *dir = opendir(path);
if (!dir) return;
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
char fullpath[1024];
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
struct stat st;
stat(fullpath, &st);
if (S_ISDIR(st.st_mode)) {
printf("[DIR] %s\n", fullpath);
list_dir(fullpath); // 递归
} else {
printf("[FILE] %s\n", fullpath);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
const char *path = argc > 1 ? argv[1] : ".";
list_dir(path);
return 0;
}
. 和 .. 是什么?.:当前目录..:上级目录readdir 返回的是文件名,不是完整路径需要自己拼接路径。
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
find /path/to/dir
ls -R /path/to/dir
如果你需要:
可以告诉我,我可以直接给你对应代码。