在 Ubuntu 下使用 opendir()(目录操作函数)时,它来自 POSIX 标准库,不需要额外安装第三方库,只需要包含正确的头文件并链接标准库即可。
#include <dirent.h> // opendir, readdir, closedir
#include <stdio.h> // printf 等
#include <stdlib.h> // exit 等
#include <dirent.h>
#include <stdio.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
opendir属于libc,默认已链接,一般不需要加-l参数。
如果你是 C++ 文件:
g++ test.cpp -o test
add_executable(test test.c)
# 通常不需要额外 target_link_libraries
opendir未声明✅ 检查是否少了:
#include <dirent.h>
✅ 确保路径存在,或用 "." 表示当前目录
| 函数 | 作用 |
|---|---|
opendir() |
打开目录 |
readdir() |
读取目录项 |
closedir() |
关闭目录 |
scandir() |
高级目录遍历 |
如果你是在 C++ / CMake / Makefile / 交叉编译 场景下遇到问题,可以告诉我具体报错信息。