在 Ubuntu(Linux)里,copendir 不是标准函数,你可能想问的是 如何遍历目录(类似 opendir/readdir/closedir),或者 如何“复制目录”。下面分几种常见情况说明。
这是 Linux 下最标准的做法,使用 dirent.h。
#include <stdio.h>
#include <dirent.h>
#include <stdlib.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 listdir.c -o listdir
./listdir
Linux 没有 copendir(),复制目录需要:
opendir 打开源目录readdir 读取内容open/read/writemkdir#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
void copy_file(const char *src, const char *dst) {
int fd_src = open(src, O_RDONLY);
int fd_dst = open(dst, O_WRONLY | O_CREAT | O_TRUNC, 0644);
char buf[4096];
ssize_t n;
while ((n = read(fd_src, buf, sizeof(buf))) > 0) {
write(fd_dst, buf, n);
}
close(fd_src);
close(fd_dst);
}
void copy_dir(const char *src, const char *dst) {
mkdir(dst, 0755);
DIR *dir = opendir(src);
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
char src_path[512], dst_path[512];
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 {
copy_file(src_path, dst_path);
}
}
closedir(dir);
}
int main() {
copy_dir("test", "test_copy");
return 0;
}
不需要写 C 程序:
cp -r src_dir dst_dir
❌ 没有 copendir 这个函数
✅ 正确的是:
opendirreaddirclosedir如果你是在 Windows 看到过类似 copendir,那是第三方封装,不是 Linux API。
你可以告诉我:
我可以直接给你一个可用的完整版本。