在 Ubuntu(Linux)下使用 opendir() 函数,需要包含以下头文件:
#include <sys/types.h>
#include <dirent.h>
<dirent.h>:必须,定义了 DIR、struct dirent 以及 opendir()、readdir()、closedir() 等函数声明。<sys/types.h>:通常也建议包含,定义了 ino_t 等类型(很多系统头文件已间接包含,但显式写上更规范、可移植性更好)。#include <stdio.h>
#include <sys/types.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
如果你还需要 stat()、文件属性相关功能,可以再包含 <sys/stat.h> 和 <unistd.h>。