在 Debian(以及其它 Linux 发行版)上,opendir 是 POSIX 标准 C 库函数,由 glibc 提供,用于打开一个目录流。下面从“能不能直接调用”“怎么用”“示例”“编译运行”几个方面说明。
opendir 定义在:
#include <dirent.h>
#include <sys/types.h>
DIR *opendir(const char *name);
DIR *(目录流)NULL,并设置 errno⚠️ 注意:opendir 是 C 库函数,不是 shell 命令,不能在终端直接“调用”,只能通过 C 程序调用。
Debian 默认已具备:
检查编译器:
gcc --version
如果没有 gcc:
sudo apt update
sudo apt install build-essential
#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[]) {
const char *path = argc > 1 ? argv[1] : ".";
DIR *dir = opendir(path);
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;
}
保存为 listdir.c
gcc listdir.c -o listdir
./listdir /etc
open:打开文件,返回 int fdopendir:打开目录,返回 DIR */root、/proc/* 等:需要权限不是,所有 Linux / Unix / POSIX 系统 都支持。
如果你不想写 C,可以用:
ls
或
find . -maxdepth 1
但那是 shell 命令,不是 opendir。
如果你有以下需求,我可以继续细讲:
openat / fdopendir 的区别