在 Debian(以及一般的 Linux)下,遍历目录通常有两种常见方式:
opendir / readdir(你提到的 copendir 应该是 opendir)下面分别说明。
lsls /path/to/dir
递归遍历:
ls -R /path/to/dir
find(最常用)find /path/to/dir
只列目录:
find /path/to/dir -type d
for 循环for f in /path/to/dir/*; do
echo "$f"
done
opendir 遍历目录(系统编程)你提到的应该是 opendir + readdir。
#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
如果需要递归遍历子目录,可以:
entry->d_type == DT_DIR. 和 ..示例片段:
if (entry->d_type == DT_DIR &&
strcmp(entry->d_name, ".") != 0 &&
strcmp(entry->d_name, "..") != 0) {
char path[1024];
snprintf(path, sizeof(path), "%s/%s", dirname, entry->d_name);
list_dir(path);
}
copendir 不存在,正确的是 opendirreaddir 返回的是 struct dirent *closedir如果你是:
findopendir/readdir我可以直接给你对应版本。