在 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
<dirent.h>readdir(), closedir(), rewinddir() 也都在 <dirent.h> 中<stdio.h>(perror)如果你是在写 C++,同样需要 #include <dirent.h>(不是 <dirent>)。
需要我给你一个完整的目录遍历示例吗?