copendir()
函數本身并不支持遞歸遍歷子目錄
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
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 = "/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()
函數將文件復制到目標目錄。