coprend 函數是用于復制目錄的遞歸函數,通常在 Linux 系統編程中使用。它允許你將一個目錄及其所有內容(包括子目錄和文件)復制到另一個位置。下面是一個簡單的示例,演示如何使用 coprend 函數:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
// 遞歸復制目錄
int coprend(const char *src, const char *dest) {
DIR *dir = opendir(src);
if (!dir) {
perror("opendir");
return -1;
}
struct stat st;
if (stat(dest, &st) == -1) {
// 如果目標目錄不存在,則創建
mkdir(dest, 0755);
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue; // 跳過當前目錄和父目錄
}
char src_path[1024], dest_path[1024];
snprintf(src_path, sizeof(src_path), "%s/%s", src, entry->d_name);
snprintf(dest_path, sizeof(dest_path), "%s/%s", dest, entry->d_name);
if (stat(src_path, &st) == -1) {
perror("stat");
closedir(dir);
return -1;
}
if (S_ISDIR(st.st_mode)) {
// 如果是目錄,則遞歸復制
if (coprend(src_path, dest_path) == -1) {
closedir(dir);
return -1;
}
} else {
// 如果是文件,則復制文件內容
FILE *src_file = fopen(src_path, "rb");
FILE *dest_file = fopen(dest_path, "wb");
if (!src_file || !dest_file) {
perror("fopen");
closedir(dir);
return -1;
}
char buffer[1024];
size_t bytes_read;
while ((bytes_read = fread(buffer, 1, sizeof(buffer), src_file)) > 0) {
fwrite(buffer, 1, bytes_read, dest_file);
}
fclose(src_file);
fclose(dest_file);
}
}
closedir(dir);
return 0;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <source_directory> <destination_directory>
", argv[0]);
return EXIT_FAILURE;
}
const char *src = argv[1];
const char *dest = argv[2];
if (coprend(src, dest) == 0) {
printf("Directory copied successfully.
");
} else {
fprintf(stderr, "Failed to copy directory.
");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
opendir 打開源目錄。stat 檢查目標目錄是否存在,如果不存在則創建。readdir 遍歷目錄中的每個條目。.)和父目錄(..)。coprend。編譯并運行程序,傳入源目錄和目標目錄作為參數:
gcc -o coprend coprend.c
./coprend /path/to/source /path/to/destination
請注意,這個示例代碼是一個簡單的實現,可能需要根據具體需求進行調整和優化。