在 Debian / Linux 下,copendir 不是标准函数,你可能想问的是 如何打开目录并遍历目录。
在 C 语言里,一般使用的是 opendir() / readdir() / closedir(),它们来自 <dirent.h>。
下面给你一个 完整、可编译的示例,适用于 Debian / Ubuntu / 所有 Linux。
listdir.c#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int main(int argc, char *argv[])
{
const char *path = "."; // 默认当前目录
DIR *dir;
struct dirent *entry;
if (argc > 1) {
path = argv[1];
}
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
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 EXIT_SUCCESS;
}
gcc listdir.c -o listdir
./listdir
./listdir /etc
| 函数 | 作用 |
|---|---|
opendir(path) |
打开目录 |
readdir(dir) |
读取目录项 |
closedir(dir) |
关闭目录 |
struct dirent |
目录项结构 |
struct dirent 常用成员char d_name[]; // 文件名
ino_t d_ino; // inode 号
copendir✅ 正确的是:
DIR *dir = opendir("目录路径");
如果你需要 递归遍历子目录,我也可以给你一个示例(使用 stat() 判断是否是目录)。
| 语言 | 接口 |
|---|---|
| C++ | std::filesystem::directory_iterator |
| Python | os.listdir() / os.scandir() |
| Shell | ls / find |
如果你能确认:
我可以直接给你对应的 Debian 示例。