在 Debian(或其他 Linux 系统)上,“写 copendir”通常是指自己实现一个类似 opendir() 的函数,或者使用 opendir() 来遍历目录。下面我分两种情况说明。
opendir(最常见)如果你只是想在 Debian 下用 C 语言打开并读取目录,使用标准 POSIX 接口即可。
#include <stdio.h>
#include <dirent.h>
#include <sys/types.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 dir_list.c -o dir_list
./dir_list
如果你想自己实现一个 copendir,通常有两种方式:
open() + getdents()(底层)这是 Linux 特有的系统调用。
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <linux/dirent.h>
#define BUF_SIZE 1024
int main() {
int fd = open(".", O_RDONLY | O_DIRECTORY);
if (fd < 0) {
perror("open");
return 1;
}
char buf[BUF_SIZE];
int n = syscall(SYS_getdents, fd, buf, BUF_SIZE);
if (n < 0) {
perror("getdents");
return 1;
}
struct linux_dirent *d;
for (int off = 0; off < n; ) {
d = (struct linux_dirent *)(buf + off);
printf("%s\n", d->d_name);
off += d->d_reclen;
}
close(fd);
return 0;
}
⚠️ 这种方式依赖内核结构,不推荐生产使用。
copendir你可以模仿标准库接口:
typedef struct {
DIR *dir;
} MYDIR;
MYDIR *copendir(const char *path) {
MYDIR *m = malloc(sizeof(MYDIR));
if (!m) return NULL;
m->dir = opendir(path);
if (!m->dir) {
free(m);
return NULL;
}
return m;
}
#include <dirent.h>
sudo apt install build-essential
opendir 会失败如果你说的“写 copendir”是:
opendir可以告诉我,我可以按你的场景写完整代码。