在 Ubuntu(Linux)下,使用 C 语言通过 opendir / readdir 遍历目录是很常见的做法。下面给你一个完整示例 + 步骤说明。
opendir():打开目录,返回 DIR*readdir():读取目录项,返回 struct dirent*d_type 或 stat() 区分文件和子目录closedir():关闭目录#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
编译运行:
gcc listdir.c -o listdir
./listdir
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void list_dir(const char *path) {
DIR *dir = opendir(path);
if (!dir) {
perror("opendir");
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;
stat(fullpath, &st);
if (S_ISDIR(st.st_mode)) {
printf("目录: %s\n", fullpath);
list_dir(fullpath); // 递归
} else {
printf("文件: %s\n", fullpath);
}
}
closedir(dir);
}
int main() {
list_dir(".");
return 0;
}
readdir 返回 . 和 ..必须跳过,否则会无限递归。
d_type 不一定可靠某些文件系统(如 NFS)entry->d_type == DT_UNKNOWN,需用 stat()。
遍历 /root 等目录需要 sudo。
| 函数 | 作用 |
|---|---|
opendir |
打开目录 |
readdir |
读取目录项 |
closedir |
关闭目录 |
stat |
获取文件信息 |
S_ISDIR |
判断是否为目录 |
如果你需要:
可以继续问我。