在 Ubuntu(Linux)下使用 opendir() 函数是需要包含头文件的。
opendir 是 POSIX 标准中的目录操作函数,声明在:
#include <dirent.h>
#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 test.c -o test
./test
<dirent.h>readdir, closedir, rewinddir 也都在 <dirent.h> 中如果你是在 C++ 里用,也可以 #include <dirent.h>(不是 <dirent>)。
需要我给你一个完整的“遍历目录”或“递归遍历子目录”的示例吗?