在 Debian(以及大多数 Linux 系统)里,遍历目录通常是通过 opendir / readdir / closedir 这组系统调用完成的,属于 POSIX 标准 API,C 语言里最常用。
下面给你一个完整、常见的用法示例,以及常见注意点。
readdir 遍历目录(C 语言)#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
const char *path = "."; // 要遍历的目录
DIR *dir;
struct dirent *entry;
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
gcc readdir_example.c -o readdir_example
./readdir_example
opendirDIR *opendir(const char *name);
DIR*NULLreaddirstruct dirent *readdir(DIR *dirp);
NULL 表示结束或出错struct dirent 常用字段:
char d_name[256]; // 文件名
ino_t d_ino; // inode 号
closedirint closedir(DIR *dirp);
. 和 ..readdir 会返回 . 和 ..,通常需要过滤:
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
如果你想递归遍历子目录,通常会结合 stat 判断是否是目录:
#include <sys/stat.h>
struct stat st;
stat(entry->d_name, &st);
if (S_ISDIR(st.st_mode)) {
// 是目录,递归处理
}
⚠️ 注意:递归时要处理路径拼接,避免死循环(如符号链接)
scandir(更方便)struct dirent **namelist;
int n = scandir(".", &namelist, NULL, alphasort);
for f in *; do
echo "$f"
done
❌ 忘记 closedir
❌ 把 readdir 当文件内容读取(它只读目录项)
❌ 未处理 . 和 ..
如果你需要:
告诉我你的具体需求,我可以直接给你对应的代码。