在 Ubuntu(Linux) 下,opendir 和 readdir 是配合使用的,而且是标准用法。
opendir():打开一个目录,返回一个 DIR* 指针readdir():读取目录中的一项(每次调用返回一个文件/子目录)closedir():关闭目录三者通常一起使用。
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
gcc test.c -o test
./test
readdir 会包括 . 和 ..readdir 不是线程安全的
readdir_r(已不推荐)readdir + 单线程或加锁NULLclosedir,否则会文件描述符泄漏| 函数 | 作用 |
|---|---|
opendir |
打开目录 |
readdir |
读取目录项 |
closedir |
关闭目录 |
stat |
获取文件信息 |
如果你是想问 Python / shell / C++ 里的“copendir”,或者是某个拼写错误(比如 opendir 打成了 copendir),可以告诉我,我可以更精确地回答。