在 Debian(以及其它 Linux 发行版)上,opendir 是 POSIX 标准库 <dirent.h> 提供的函数,用于打开一个目录流。下面给你一个最小可运行示例,并说明在 Debian 上如何编译。
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "用法: %s <目录>\n", argv[0]);
return 1;
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir 失败");
return 1;
}
printf("成功打开目录: %s\n", argv[1]);
closedir(dir);
return 0;
}
gcc opendir_example.c -o opendir_example
./opendir_example /etc
输出类似:
成功打开目录: /etc
opendir():打开目录readdir():读取目录项closedir():关闭目录#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[]) {
if (argc < 2) return 1;
DIR *dir = opendir(argv[1]);
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
在 Debian 上你也可以看手册:
man opendir
man readdir
如果你想看 glibc 源码示例,可以安装:
apt install glibc-source
源码通常在:
/usr/src/glibc/
如果你想要 C++ 示例、递归遍历目录,或者 用 nftw / scandir 的示例,也可以告诉我。