1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23#include <stdio.h>
24#include <stdlib.h>
25#include <unistd.h>
26#include <fcntl.h>
27#include <errno.h>
28#include <string.h>
29
30#define CHECKSUM_OFFSET (14*1024-4)
31#define BUFSIZE (16*1024)
32#define FILE_PERM (S_IRUSR | S_IWUSR | S_IRGRP \
33 | S_IWGRP | S_IROTH | S_IWOTH)
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48int main(int argc, char **argv)
49{
50 int i, len;
51 unsigned char buffer[BUFSIZE] = {0};
52 int ifd, ofd;
53 unsigned int checksum = 0, count;
54
55 if (argc != 3) {
56 printf(" %d Wrong number of arguments\n", argc);
57 exit(EXIT_FAILURE);
58 }
59
60 ifd = open(argv[1], O_RDONLY);
61 if (ifd < 0) {
62 fprintf(stderr, "%s: Can't open %s: %s\n",
63 argv[0], argv[1], strerror(errno));
64 exit(EXIT_FAILURE);
65 }
66
67 ofd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, FILE_PERM);
68 if (ifd < 0) {
69 fprintf(stderr, "%s: Can't open %s: %s\n",
70 argv[0], argv[2], strerror(errno));
71 if (ifd)
72 close(ifd);
73 exit(EXIT_FAILURE);
74 }
75
76 len = lseek(ifd, 0, SEEK_END);
77 lseek(ifd, 0, SEEK_SET);
78
79 count = (len < CHECKSUM_OFFSET) ? len : CHECKSUM_OFFSET;
80
81 if (read(ifd, buffer, count) != count) {
82 fprintf(stderr, "%s: Can't read %s: %s\n",
83 argv[0], argv[1], strerror(errno));
84
85 if (ifd)
86 close(ifd);
87 if (ofd)
88 close(ofd);
89
90 exit(EXIT_FAILURE);
91 }
92
93 for (i = 0, checksum = 0; i < CHECKSUM_OFFSET; i++)
94 checksum += buffer[i];
95
96 memcpy(&buffer[CHECKSUM_OFFSET], &checksum, sizeof(checksum));
97
98 if (write(ofd, buffer, BUFSIZE) != BUFSIZE) {
99 fprintf(stderr, "%s: Can't write %s: %s\n",
100 argv[0], argv[2], strerror(errno));
101
102 if (ifd)
103 close(ifd);
104 if (ofd)
105 close(ofd);
106
107 exit(EXIT_FAILURE);
108 }
109
110 if (ifd)
111 close(ifd);
112 if (ofd)
113 close(ofd);
114
115 return EXIT_SUCCESS;
116}
117