在 Debian(以及所有 Linux/Unix 系统) 下,使用 C 语言遍历目录通常是用 opendir + readdir + closedir,而不是“copendir”(标准库里没有 copendir,可能是拼写或记混了)。
下面给你一个完整可运行的示例。
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
DIR *dir;
struct dirent *entry;
if (argc < 2) {
printf("Usage: %s <directory>\n", argv[0]);
return 1;
}
dir = opendir(argv[1]);
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 /etc
如果你是想遍历整个目录树,需要递归:
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void list_dir(const char *path)
{
DIR *dir = opendir(path);
struct dirent *entry;
char fullpath[1024];
struct stat st;
if (!dir) return;
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);
if (stat(fullpath, &st) == 0 && 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[])
{
if (argc < 2) return 1;
list_dir(argv[1]);
return 0;
}
copendiropendirreaddirclosedircopendir,可能是:
FindFirstFile. 和 .. 需要手动过滤readdir_r(旧)readdir如果你是 想在 Debian 命令行遍历目录:
for f in /etc/*; do
echo "$f"
done
或递归:
find /etc -type f
如果你说的是 某种特定语言(Python / Shell / C++) 或 “copendir”来自某个库,可以告诉我,我可以精准解答。