在 Debian(以及其它 Linux 系统)中使用 opendir() 函数,需要包含以下头文件:
#include <sys/types.h>
#include <dirent.h>
opendir() 原型在 <dirent.h> 中DIR * 类型以及 struct dirent 相关定义也主要在 <dirent.h><sys/types.h> 通常用于确保 off_t、ino_t 等类型正确(很多示例代码会一起包含)#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
if (!dir) {
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
如果你是在 C++ 里用,也可以写成:
#include <dirent.h>
#include <sys/types.h>
需要的话我也可以告诉你 readdir、scandir 或 C++17 std::filesystem 的用法。