在 Debian(Linux) 下,opendir() 是 POSIX 标准库函数,用于打开一个目录流,定义在 <dirent.h> 中。它并不是 Debian 独有的,而是 glibc 提供的。
下面从 使用方式 和 底层实现原理 两个层面说明。
#include <dirent.h>
DIR *opendir(const char *name);
#include <stdio.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;
}
编译:
gcc test.c -o test
opendir() 的本质流程是:
(来自 glibc 源码 sysdeps/unix/opendir.c)
DIR *
opendir (const char *name)
{
int fd = open(name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (fd == -1)
return NULL;
DIR *dirp = malloc(sizeof(DIR));
if (dirp == NULL) {
close(fd);
return NULL;
}
dirp->fd = fd;
dirp->offset = 0;
dirp->data = NULL;
return dirp;
}
✅ 关键点:
DIR 是 glibc 的封装结构getdents64() 完成在 Debian / Linux 中:
getdents(unsigned int fd, struct linux_dirent *dirp, unsigned int count)
或
getdents64()
readdir() 内部会调用这些系统调用。
| 函数 | 类型 |
|---|---|
| opendir | glibc 库函数 |
| open | 系统调用 |
| getdents | 系统调用 |
| readdir | glibc 库函数 |
man 3 opendir
man 2 getdents
apt source glibc
路径示例:
glibc-2.xx/sysdeps/unix/opendir.c
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
DIR *my_opendir(const char *path) {
int fd = open(path, O_RDONLY | O_DIRECTORY);
if (fd < 0) return NULL;
DIR *dir = malloc(sizeof(DIR));
dir->fd = fd;
return dir;
}
❌ 用 fopen() 打开目录
❌ 忘记 closedir()
❌ 在 NFS 目录上假设顺序稳定
如果你是想:
可以告诉我,我可以按你的方向深入讲。