在 Ubuntu(Linux)下,如果你说的是 用 C 语言读取目录,通常是用 opendir / readdir 这套 POSIX 接口,而不是“copendir”。下面给你一个完整、可直接编译运行的示例。
listdir.c#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("用法: %s <目录>\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
输出示例:
.
..
passwd
hosts
resolv.conf
...
#include <sys/stat.h>
#include <string.h>
// 在 while 中加判断
struct stat st;
char path[1024];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) {
printf("%s\n", entry->d_name);
}
| 函数 | 作用 |
|---|---|
opendir() |
打开目录,返回 DIR* |
readdir() |
读取一个目录项 |
closedir() |
关闭目录 |
struct dirent |
目录项结构 |
os.listdir() 或 pathlibstd::filesystem::directory_iteratorls / find如果你说的 “copendir” 是某个特定库(比如某些封装库),可以告诉我具体名称,我可以给你对应的用法。