opendir 是 POSIX 标准库 中的函数,不是 Ubuntu 特有的命令或工具。在 Ubuntu(以及大多数 Linux)上,它用于 打开目录流,通常和 readdir、closedir 一起使用。
下面给你一个完整、规范的说明和示例。
opendir 定义在:
#include <dirent.h>
函数原型:
DIR *opendir(const char *name);
作用:
打开一个目录,返回一个 DIR* 目录流指针,用于后续读取目录内容。
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
int main() {
const char *path = "."; // 当前目录
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return EXIT_SUCCESS;
}
gcc listdir.c -o listdir
./listdir
| 函数 | 作用 |
|---|---|
opendir |
打开目录 |
readdir |
读取目录项 |
closedir |
关闭目录 |
rewinddir |
重置目录流 |
seekdir / telldir |
定位目录流 |
DIR *dir = opendir("/not/exist");
if (!dir) {
perror("opendir");
}
可能原因:
. 和 ..if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
✅ 可以,但更推荐:
std::filesystemopendir#include <filesystem>
#include <iostream>
int main() {
for (auto &p : std::filesystem::directory_iterator(".")) {
std::cout << p.path() << std::endl;
}
}
编译:
g++ -std=c++17 list.cpp -o list
在 Ubuntu 上调用
opendir,就是在 C/C++ 程序中使用 POSIX 目录操作 API,包含 `<dirent.h> 并链接标准库即可。
如果你是想:
可以继续问我,我可以按你的使用场景详细展开。