在 Ubuntu(Linux)下使用 opendir 函数,需要包含以下头文件:
#include <sys/types.h>
#include <dirent.h>
opendir 用于打开一个目录,返回一个 DIR *sys/types.h:定义 ino_t 等基本类型(有些实现中可能需要)dirent.h:声明 opendir、readdir、closedir 以及 DIR、struct dirent#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、scandir 或递归遍历目录,也可以告诉我。