在Linux中,您可以使用copendir()
函數從給定目錄中復制所有子目錄
#include <stdio.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 path[PATH_MAX];
// 打開源目錄
if ((src_dir = opendir(src)) == NULL) {
perror("opendir");
return -1;
}
// 創建目標目錄
if (mkdir(dest, 0777) != 0) {
perror("mkdir");
closedir(src_dir);
return -1;
}
// 復制源目錄中的所有子目錄
while ((entry = readdir(src_dir)) != NULL) {
if (entry->d_type == DT_DIR) {
snprintf(path, sizeof(path), "%s/%s", src, entry->d_name);
if (copendir(path, dest) == -1) {
perror("copendir");
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("Directories copied successfully.\n");
} else {
printf("Error copying directories.\n");
}
return 0;
}
這個程序首先打開源目錄,然后創建目標目錄。接下來,它遍歷源目錄中的所有子目錄,并使用copendir()
函數遞歸地復制它們到目標目錄。最后,它關閉源目錄。
請注意,您需要將/path/to/source
和/path/to/destination
替換為實際的源和目標目錄路徑。