在 Ubuntu(Linux)里,copendir 不是一个标准函数,你可能指的是 opendir / readdir / closedir 这一套 目录遍历 API。下面我按「从入门到实践」给你一个完整学习路线。
copendir,应该是 opendir标准 POSIX 目录操作函数是:
#include <dirent.h>
DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);
✅ 这是 Ubuntu / Linux 下学习目录操作的正确入口。
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
gcc listdir.c -o listdir
./listdir
DIR *FILE *struct dirent常用字段:
struct dirent {
ino_t d_ino;
off_t d_off;
unsigned short d_reclen;
unsigned char d_type; // 文件类型(DT_REG / DT_DIR)
char d_name[256];
};
⚠️ d_type 不一定在所有文件系统上都可靠(如某些网络文件系统)
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
struct stat st;
stat(entry->d_name, &st);
if (S_ISDIR(st.st_mode))
printf("[DIR] %s\n", entry->d_name);
else
printf("[FILE] %s\n", entry->d_name);
}
closedir(dir);
return 0;
}
✅ 推荐用 stat() 判断类型,比 d_type 更可靠
closedirclosedir(dir);
readdir 当成安全的readdir 不是线程安全readdir_r(已废弃)或 readdir + 锁. 和 ..if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
man opendir
man readdir
man closedir
man dirent
如果提示没有:
sudo apt install man-db manpages-dev
ls 命令| 方法 | 说明 |
|---|---|
opendir/readdir |
POSIX,最常用 |
glob() |
通配符匹配 |
nftw() |
高级目录遍历 |
find 命令 |
命令行工具 |
copendir 出现在某处可能是:
你可以把代码贴出来,我可以帮你确认。
Ubuntu 下学习目录操作,从
man opendir开始,用opendir + readdir + closedir,再结合stat()。
如果你愿意,我可以:
opendir 和 find / glob你想从哪一步开始?