在 Ubuntu(Linux)下使用 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
opendir() 属于 POSIX 标准,不是 C 标准库opendir, readdir, closedir → <dirent.h>stat(常用配合) → <sys/stat.h>perror → <stdio.h>如果你是在 C++ 里用,也可以:
#include <dirent.h>
需要我给你一个递归遍历目录的例子吗?