在 Debian(其实是标准 POSIX/Linux C 语言环境)中,opendir 用于打开一个目录,通常和 readdir、closedir 配合使用。下面给你一个完整可编译的示例。
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
if (argc < 2) {
fprintf(stderr, "用法: %s <目录>\n", argv[0]);
return 1;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
gcc opendir_example.c -o opendir_example
./opendir_example /etc
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat st;
char path[1024];
dir = opendir(argv[1]);
while ((entry = readdir(dir)) != NULL) {
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
stat(path, &st);
if (S_ISREG(st.st_mode)) {
printf("文件: %s\n", entry->d_name);
}
}
closedir(dir);
}
opendir:打开目录,返回 DIR*readdir:读取目录项closedir:关闭目录#include <dirent.h>
如果你想要 C++ 示例、递归遍历目录 或 过滤特定后缀文件,也可以告诉我。