在 Debian(以及其它 Linux 发行版、POSIX 系统)中,opendir 函数的头文件是:
#include <dirent.h>
opendir 用于打开一个目录,返回一个 DIR *<dirent.h> 中:
opendirreaddirclosedirrewinddirseekdirtelldir#include <dirent.h>
#include <stdio.h>
int main(void) {
DIR *dir = opendir("/tmp");
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
在 Debian 上直接用 gcc 编译即可:
gcc test.c -o test
如果你是在写 C++,同样也是包含 <dirent.h>(或使用 <sys/types.h> + <dirent.h>)。
需要我补充 opendir 与 fdopendir 的区别,或目录遍历的完整示例吗?