1 #include <stdio.h>
2 #include <io_utils.h>
3 #include <time_utils.h>
4 #include <locale.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, "r");
20 if (!src_file) {
21 return COPY_SRC_OPEN_ERROR;
22 }
23
24 FILE *dest_file = fopen(dest, "w");
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 #define BUFFER_SIZE 512
58
59 int CopyFile2(char const *src, char const *dest) {
60 if (!src || !dest) {
61 // 参数至少有一个为 NULL
62 return COPY_ILLEGAL_ARGUMENTS;
63 }
64
65 FILE *src_file = fopen(src, "r");
66 if (!src_file) {
67 // src 打开失败
68 return COPY_SRC_OPEN_ERROR;
69 }
70
71 FILE *dest_file = fopen(dest, "w");
72 if (!dest_file) {
73 // dest 打开失败,记得关闭 src
74 fclose(src_file);
75 return COPY_DEST_OPEN_ERROR;
76 }
77
78 int result = COPY_SUCCESS;
79 char buffer[BUFFER_SIZE];
80 char *next;
81 while (1) {
82 next = fgets(buffer, BUFFER_SIZE, src_file);
83 if (!next) {
84 if (ferror(src_file)) {
85 result = COPY_SRC_READ_ERROR;
86 } else if(feof(src_file)) {
87 result = COPY_SUCCESS;
88 } else {
89 result = COPY_UNKNOWN_ERROR;
90 }
91 break;
92 }
93
94 if (fputs(next, dest_file) == EOF) {
95 result = COPY_DEST_WRITE_ERROR;
96 break;
97 }
98 }
99
100 fclose(src_file);
101 fclose(dest_file);
102 return result;
103 }
104
105 int main() {
106 setlocale(LC_ALL, "zh_CN.utf-8");
107 char *srcs[] = {"data/io_utils.h", "data/三国演义.txt"};
108 char *dsts[] = {"data_copy/io_utils.h", "data_copy/三国演义.txt"};
109
110 for (int i = 0; i < 2; ++i) {
111 TimeCost(NULL);
112 CopyFile(srcs[i], dsts[i]);
113 TimeCost(srcs[i]);
114 PRINT_IF_ERROR("CopyFile: %s", srcs[i]);
115 }
116
117 for (int i = 0; i < 2; ++i) {
118 TimeCost(NULL);
119 CopyFile2(srcs[i], dsts[i]);
120 TimeCost(srcs[i]);
121 PRINT_IF_ERROR("CopyFile2: %s", srcs[i]);
122 }
123 return 0;
124 }