在 Ubuntu(Linux)下,如果你用的是 C 语言 的 opendir / readdir 来遍历目录,一般流程是这样的:
opendir() 打开目录readdir() 逐个读取目录项closedir() 关闭目录#include <stdio.h>
#include <dirent.h>
#include <string.h>
int main(int argc, char *argv[])
{
const char *path = "."; // 当前目录
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 跳过 . 和 ..
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
gcc listdir.c -o listdir
./listdir
#include <sys/stat.h>
struct stat st;
char fullpath[256];
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
stat(fullpath, &st);
if (S_ISDIR(st.st_mode))
printf("[DIR] %s\n", entry->d_name);
else
printf("[FILE] %s\n", entry->d_name);
可以在 S_ISDIR 时再次调用 opendir
std::filesystem::directory_iteratorfor f in *; do ...os.listdir / os.scandir如果你说的 “copendir” 是指某个特定库(比如某些封装库),可以告诉我具体名称,我可以给更针对性的示例。