在 Debian(以及其它 Linux 系统)上使用 opendir() 函数,需要包含以下头文件:
#include <sys/types.h>
#include <dirent.h>
<sys/types.h>:定义了 DIR * 等类型(虽然现代系统中 <dirent.h> 通常已经包含,但规范写法建议加上)<dirent.h>:声明了 opendir()、readdir()、closedir() 等目录操作函数#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;
}
在 Debian 上直接用 gcc 编译即可,不需要额外链接库:
gcc test.c -o test
如果你是在写 Makefile 或遇到具体报错,也可以把错误信息发出来。