copendir()
函数本身并不支持递归遍历子目录
#include#include #include #include #include int copendir(const char *src, const char *dest) { DIR *src_dir, *dest_dir; struct dirent *entry; struct stat statbuf; char src_path[PATH_MAX], dest_path[PATH_MAX]; // 构建源目录和目标目录的完整路径 snprintf(src_path, sizeof(src_path), "%s/%s", src, ""); snprintf(dest_path, sizeof(dest_path), "%s/%s", dest, ""); // 打开源目录 if ((src_dir = opendir(src_path)) == NULL) { perror("opendir"); return -1; } // 创建目标目录 if (mkdir(dest_path, 0777) == -1) { perror("mkdir"); closedir(src_dir); return -1; } // 遍历源目录 while ((entry = readdir(src_dir)) != NULL) { // 构建源文件和目标文件的完整路径 snprintf(src_path, sizeof(src_path), "%s/%s", src_path, entry->d_name); snprintf(dest_path, sizeof(dest_path), "%s/%s", dest_path, entry->d_name); // 获取源文件的元数据 if (stat(src_path, &statbuf) == -1) { perror("stat"); continue; } // 如果是目录,则递归遍历子目录 if (S_ISDIR(statbuf.st_mode)) { if (copendir(src_path, dest_path) == -1) { perror("copendir"); closedir(src_dir); return -1; } } else { // 复制文件 if (link(src_path, dest_path) == -1) { perror("link"); closedir(src_dir); return -1; } } } // 关闭源目录 closedir(src_dir); return 0; } int main() { const char *src = "https://www.yisu.com/path/to/source"; const char *dest = "/path/to/destination"; if (copendir(src, dest) == 0) { printf("Copying directory %s to %s succeeded.\n", src, dest); } else { printf("Copying directory %s to %s failed.\n", src, dest); } return 0; }
这个程序首先打开源目录,然后遍历其中的每个条目。如果条目是一个目录,它会递归地调用自身来处理子目录。如果条目是一个文件,它会使用 link()
函数将文件复制到目标目录。