copirdir
是一個用于復制目錄及其內容的函數,它在 Linux 系統編程中非常有用。以下是一個使用 copirdir
函數的簡單示例:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
int copirdir(const char *src, const char *dest) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
char srcpath[PATH_MAX], destpath[PATH_MAX];
if (!(dir = opendir(src))) {
perror("opendir");
return -1;
}
if (mkdir(dest, statbuf.st_mode) == -1) {
perror("mkdir");
closedir(dir);
return -1;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
snprintf(srcpath, sizeof(srcpath), "%s/%s", src, entry->d_name);
snprintf(destpath, sizeof(destpath), "%s/%s", dest, entry->d_name);
if (lstat(srcpath, &statbuf) == -1) {
perror("lstat");
closedir(dir);
return -1;
}
if (S_ISDIR(statbuf.st_mode)) {
if (copirdir(srcpath, destpath) == -1)
return -1;
} else {
if (copyfile(srcpath, destpath) == -1)
return -1;
}
}
closedir(dir);
return 0;
}
int copyfile(const char *src, const char *dest) {
FILE *src_file, *dest_file;
int c;
src_file = fopen(src, "rb");
if (!src_file) {
perror("fopen");
return -1;
}
dest_file = fopen(dest, "wb");
if (!dest_file) {
perror("fopen");
fclose(src_file);
return -1;
}
while ((c = fgetc(src_file)) != EOF) {
if (fputc(c, dest_file) == EOF) {
perror("fputc");
fclose(src_file);
fclose(dest_file);
return -1;
}
}
fclose(src_file);
fclose(dest_file);
return 0;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <source_directory> <destination_directory>\n", argv[0]);
return 1;
}
if (copirdir(argv[1], argv[2]) == 0) {
printf("Directory copied successfully.\n");
} else {
fprintf(stderr, "Failed to copy directory.\n");
return 1;
}
return 0;
}
這個示例程序接受兩個命令行參數:源目錄和目標目錄。它使用 copirdir
函數遞歸地復制源目錄及其內容到目標目錄。如果復制成功,程序將輸出 “Directory copied successfully.”,否則輸出 “Failed to copy directory.”。
要編譯此程序,請將其保存為 copirdir_example.c
,然后在終端中運行以下命令:
gcc -o copirdir_example copirdir_example.c
現在,您可以使用以下命令運行程序:
./copirdir_example /path/to/source/directory /path/to/destination/directory
請注意,此示例程序僅用于演示目的,可能無法處理所有邊緣情況。在實際應用中,您可能需要根據您的需求對其進行修改。