copendir()
是一個用于復制目錄的函數,它可以在 Linux 系統中使用
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
int copendir(const char *src, const char *dest) {
int src_fd, dest_fd;
struct stat src_stat;
// 打開源目錄
if ((src_fd = open(src, O_RDONLY)) == -1) {
perror("open");
return -1;
}
// 獲取源目錄的狀態信息
if (fstat(src_fd, &src_stat) == -1) {
perror("fstat");
close(src_fd);
return -1;
}
// 檢查目標目錄是否存在,如果不存在則創建
if (access(dest, F_OK) == -1) {
if (mkdir(dest, src_stat.st_mode & 0777) == -1) {
perror("mkdir");
close(src_fd);
return -1;
}
}
// 復制源目錄到目標目錄
if (copydir(src_fd, dest, src_stat.st_mode & 0777) == -1) {
perror("copydir");
close(src_fd);
return -1;
}
// 關閉文件描述符
close(src_fd);
return 0;
}
在這個示例中,我們首先打開源目錄,然后獲取其狀態信息。接下來,我們檢查目標目錄是否存在,如果不存在則創建它。最后,我們使用 copydir()
函數復制源目錄到目標目錄。如果在任何步驟中遇到錯誤,我們將處理錯誤并返回 -1。否則,我們返回 0 表示成功。
請注意,這個示例僅適用于 POSIX 兼容系統,如 Linux 和 macOS。在其他系統上,您可能需要使用不同的函數或方法來處理錯誤目錄。