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#include "libbb.h"
33#include "common_bufsiz.h"
34
35enum { SUM_BSD, PRINT_NAME, SUM_SYSV };
36
37
38
39
40
41static unsigned sum_file(const char *file, unsigned type)
42{
43 unsigned long long total_bytes = 0;
44 int fd, r;
45
46 unsigned s = 0;
47
48#define buf bb_common_bufsiz1
49 setup_common_bufsiz();
50
51 fd = open_or_warn_stdin(file);
52 if (fd == -1)
53 return 0;
54
55 while (1) {
56 size_t bytes_read = safe_read(fd, buf, COMMON_BUFSIZE);
57
58 if ((ssize_t)bytes_read <= 0) {
59 r = (fd && close(fd) != 0);
60 if (!bytes_read && !r)
61
62 break;
63 bb_simple_perror_msg(file);
64 return 0;
65 }
66
67 total_bytes += bytes_read;
68 if (type >= SUM_SYSV) {
69 do s += buf[--bytes_read]; while (bytes_read);
70 } else {
71 r = 0;
72 do {
73 s = (s >> 1) + ((s & 1) << 15);
74 s += buf[r++];
75 s &= 0xffff;
76 } while (--bytes_read);
77 }
78 }
79
80 if (type < PRINT_NAME)
81 file = "";
82 if (type >= SUM_SYSV) {
83 r = (s & 0xffff) + ((s & 0xffffffff) >> 16);
84 s = (r & 0xffff) + (r >> 16);
85 printf("%u %llu %s\n", s, (total_bytes + 511) / 512, file);
86 } else
87 printf("%05u %5llu %s\n", s, (total_bytes + 1023) / 1024, file);
88 return 1;
89#undef buf
90}
91
92int sum_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
93int sum_main(int argc UNUSED_PARAM, char **argv)
94{
95 unsigned n;
96 unsigned type = SUM_BSD;
97
98 n = getopt32(argv, "sr");
99 argv += optind;
100 if (n & 1) type = SUM_SYSV;
101
102 if (n & 2) type = SUM_BSD;
103
104 if (!argv[0]) {
105
106 n = sum_file("-", type);
107 } else {
108
109
110
111 type += (argv[1] || type == SUM_SYSV);
112 n = 1;
113 do {
114 n &= sum_file(*argv, type);
115 } while (*++argv);
116 }
117 return !n;
118}
119