-
Notifications
You must be signed in to change notification settings - Fork 24
/
error_handle.c
111 lines (91 loc) · 1.64 KB
/
error_handle.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int file_copy1(char *src, char *dst)
{
FILE *fd_src, *fd_dst;
char *buf;
size_t total = 0;
if (src == NULL || dst == NULL)
return -1;
printf("copy %s to %s\n", src, dst);
fd_src = fopen(src, "r");
if (fd_src == NULL)
return -1;
fd_dst = fopen(dst, "w");
if (fd_dst == NULL) {
fclose(fd_src);
return -1;
}
buf = calloc(4096, sizeof(*buf));
if (buf == NULL) {
fclose(fd_src);
fclose(fd_dst);
return -1;
}
total = 0;
do {
int c;
c = fread(buf, sizeof(*buf), 4096, fd_src);
if (c == 0)
break;
c = fwrite(buf, sizeof(*buf), c, fd_dst);
if (c == 0)
break;
total += c;
} while (1);
free(buf);
fclose(fd_src);
fclose(fd_dst);
return total;
}
int file_copy2(char *src, char *dst)
{
FILE *fd_src, *fd_dst;
char *buf;
size_t total = -1;
if (src == NULL || dst == NULL)
goto error_src;
printf("copy %s to %s\n", src, dst);
fd_src = fopen(src, "r");
if (fd_src == NULL)
goto error_src;
fd_dst = fopen(dst, "w");
if (fd_dst == NULL)
goto error_dst;
buf = calloc(4096, sizeof(*buf));
if (buf == NULL)
goto error_buf;
total = 0;
do {
int c;
c = fread(buf, sizeof(*buf), 4096, fd_src);
if (c == 0)
break;
c = fwrite(buf, sizeof(*buf), c, fd_dst);
if (c == 0)
break;
total += c;
} while (1);
free(buf);
error_buf:
fclose(fd_dst);
error_dst:
fclose(fd_src);
error_src:
return total;
}
int main(int argc, char *argv[])
{
int c;
int (*fp)(char *src, char *dst);
if (argc != 3) {
printf("usage: ./a.out SRC DEST\n");
return 1;
}
fp = file_copy1;
c = fp(argv[1], argv[2]);
if (c < 0)
printf("failed\n");
return 0;
}