在 Linux(包括 Ubuntu)里,opendir() 并不是 Ubuntu 自己“发明”的,而是 POSIX 标准 规定的目录操作接口之一。你之所以会在 Ubuntu 下看到或用它,主要有下面几个原因:
opendir() 是读取目录的标准方式在 Linux 中,目录本身也是一种“文件”,但不能用 open() + read() 直接读。
要遍历目录内容,必须使用专门的目录操作函数:
DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);
这是 POSIX 标准(IEEE 1003.1) 规定的,Ubuntu 作为 Linux 发行版自然遵循这个标准。
open() 打开目录?虽然目录在 VFS 层面确实可以用 open() 打开,但:
read() 读目录是 未定义行为所以:
✅ open():用于普通文件
✅ opendir():专门用于目录
❌ 不能用 read() 读目录
opendir() 背后的机制在 Ubuntu / Linux 中:
opendir() 内部会调用 open() + getdents() 系统调用DIR *(目录流)readdir() 会返回 struct dirent(目录项)简化流程:
opendir()
↓
open(dir)
↓
readdir()
↓
getdents()
遵循 POSIX,保证程序在:
都能编译运行。
Ubuntu 里大量程序依赖 opendir(),例如:
lsfinddurm -r| 系统 | 遍历目录方式 |
|---|---|
| Linux / Ubuntu | opendir() / readdir() |
| Windows | FindFirstFile() / FindNextFile() |
所以 opendir() 是 类 Unix 系统的标准做法。
ls 等命令例如:
strace ls
你会看到:
openat(...)
getdents(...)
Ubuntu 使用
opendir()是因为它是 POSIX 标准规定的、安全且可移植的目录遍历接口,而不是 Ubuntu 自己的设计。
如果你愿意,我可以:
opendir() 的最小示例opendir() 和 open() + getdents()