C语言学习:复制文件

 

 1 #include <stdio.h>
 2 #include <io_utils.h>
 3 #include <errno.h>
 4 #include <string.h>
 5 
 6 #define COPY_SUCCESS 0
 7 #define COPY_ILLEGAL_ARGUMENTS -1
 8 #define COPY_SRC_OPEN_ERROR -2
 9 #define COPY_SRC_READ_ERROR -3
10 #define COPY_DEST_OPEN_ERROR -4
11 #define COPY_DEST_WRITE_ERROR -5
12 #define COPY_UNKNOWN_ERROR -100
13 
14 int CopyFile(char const *src, char const *dest) {
15   if (!src || !dest) {
16     return COPY_ILLEGAL_ARGUMENTS;
17   }
18 
19   FILE *src_file = fopen(src, "rb");
20   if (!src_file) {
21     return COPY_SRC_OPEN_ERROR;
22   }
23 
24   FILE *dest_file = fopen(dest, "wb");
25   if (!dest_file) {
26     fclose(src_file);
27     return COPY_DEST_OPEN_ERROR;
28   }
29 
30   int result;
31 
32   while (1) {
33     int next = fgetc(src_file);
34     if (next == EOF) {
35       if (ferror(src_file)) {
36         result = COPY_SRC_READ_ERROR;
37       } else if(feof(src_file)) {
38         result = COPY_SUCCESS;
39       } else {
40         result = COPY_UNKNOWN_ERROR;
41       }
42       break;
43     }
44 
45     if (fputc(next, dest_file) == EOF) {
46       result = COPY_DEST_WRITE_ERROR;
47       break;
48     }
49   }
50 
51   fclose(src_file);
52   fclose(dest_file);
53 
54   return result;
55 }
56 
57 int main() {
58   int result = CopyFile("data/io_utils.h", "data_copy/io_utils.h");
59   PRINT_INT(result);
60   result = CopyFile("data/logo.bmp", "data_copy/logo.bmp");
61   PRINT_INT(result);
62   return 0;
63 }
View Code

 

 

 

posted @ 2023-02-12 15:52  泥古拉斯赵四  阅读(9)  评论(0编辑  收藏  举报