在 Debian / Linux 下,并没有一个叫 copendir 的标准函数。
你可能是想问下面几种情况之一,我分别说明一下。
在 Linux(包括 Debian)中,遍历目录使用的是 POSIX 标准接口:
#include <dirent.h>
#include <stdio.h>
int main() {
DIR *dir = opendir(".");
if (!dir) {
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() |
打开目录 |
readdir() |
读取目录项 |
closedir() |
关闭目录 |
rewinddir() |
重置目录流 |
seekdir() / telldir() |
定位目录流 |
Linux 没有 copendir,但可以用 系统调用 + 递归 实现。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
void copy_dir(const char *src, const char *dst) {
mkdir(dst, 0755);
DIR *dir = opendir(src);
if (!dir) return;
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
char src_path[1024], dst_path[1024];
snprintf(src_path, sizeof(src_path), "%s/%s", src, entry->d_name);
snprintf(dst_path, sizeof(dst_path), "%s/%s", dst, entry->d_name);
struct stat st;
lstat(src_path, &st);
if (S_ISDIR(st.st_mode)) {
copy_dir(src_path, dst_path);
} else {
// 简单复制文件(真实场景建议用 read/write)
char cmd[2048];
snprintf(cmd, sizeof(cmd), "cp '%s' '%s'", src_path, dst_path);
system(cmd);
}
}
closedir(dir);
}
你可以自己封装一个:
DIR *copendir(const char *path) {
return opendir(path);
}
或者你想实现 目录复制 + 打开 的组合逻辑,也可以封装成自己的函数。
如果你在编译时缺头文件:
sudo apt update
sudo apt install build-essential manpages-dev
查看手册:
man opendir
man readdir
✅ Debian / Linux 没有 copendir
✅ 正确做法是:
opendir + readdiropendir + 递归 + mkdir/cpcopendir() 函数如果你愿意,可以告诉我:
我可以给你更精确的示例。