1 /* vi: set sw=4 ts=4: */
3 * sum -- checksum and count the blocks in a file
4 * Like BSD sum or SysV sum -r, except like SysV sum if -s option is given.
6 * Copyright (C) 86, 89, 91, 1995-2002, 2004 Free Software Foundation, Inc.
7 * Copyright (C) 2005 by Erik Andersen <andersen@codepoet.org>
8 * Copyright (C) 2005 by Mike Frysinger <vapier@gentoo.org>
10 * Written by Kayvan Aghaiepour and David MacKenzie
11 * Taken from coreutils and turned into a busybox applet by Mike Frysinger
13 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
18 /* 1 if any of the files read were the standard input */
19 static int have_read_stdin;
21 /* Calculate and print the rotated checksum and the size in 1K blocks
22 of file FILE, or of the standard input if FILE is "-".
23 If PRINT_NAME is >1, print FILE next to the checksum and size.
24 The checksum varies depending on sizeof (int).
25 Return 1 if successful. */
26 static int bsd_sum_file(const char *file, int print_name)
29 int checksum = 0; /* The checksum mod 2^16. */
30 uintmax_t total_bytes = 0; /* The number of bytes. */
31 int ch; /* Each character read. */
34 if (LONE_DASH(file)) {
38 fp = fopen_or_warn(file, "r");
43 while ((ch = getc(fp)) != EOF) {
45 checksum = (checksum >> 1) + ((checksum & 1) << 15);
47 checksum &= 0xffff; /* Keep it within bounds. */
52 fclose_if_not_stdin(fp);
56 if (fclose_if_not_stdin(fp) == EOF) {
61 printf("%05d %5ju ", checksum, (total_bytes+1023)/1024);
70 /* Calculate and print the checksum and the size in 512-byte blocks
71 of file FILE, or of the standard input if FILE is "-".
72 If PRINT_NAME is >0, print FILE next to the checksum and size.
73 Return 1 if successful. */
74 #define MY_BUF_SIZE 8192
75 static int sysv_sum_file(const char *file, int print_name)
77 RESERVE_CONFIG_BUFFER(buf, MY_BUF_SIZE);
79 uintmax_t total_bytes = 0;
81 /* The sum of all the input bytes, modulo (UINT_MAX + 1). */
84 if (LONE_DASH(file)) {
88 fd = open(file, O_RDONLY);
94 size_t bytes_read = safe_read(fd, buf, MY_BUF_SIZE);
99 if (bytes_read == -1) {
102 RELEASE_CONFIG_BUFFER(buf);
103 if (NOT_LONE_DASH(file))
108 total_bytes += bytes_read;
110 s += buf[bytes_read];
113 if (NOT_LONE_DASH(file) && close(fd) == -1)
114 goto release_and_ret;
116 RELEASE_CONFIG_BUFFER(buf);
119 int r = (s & 0xffff) + ((s & 0xffffffff) >> 16);
120 s = (r & 0xffff) + (r >> 16);
122 printf("%d %ju ", s, (total_bytes+511)/512);
124 puts(print_name ? file : "");
129 int sum_main(int argc, char **argv)
133 int (*sum_func)(const char *, int) = bsd_sum_file;
135 /* give the bsd func priority over sysv func */
136 flags = getopt32(argc, argv, "sr");
138 sum_func = sysv_sum_file;
140 sum_func = bsd_sum_file;
143 if ((argc - optind) == 0)
144 ok = sum_func("-", 0);
146 for (ok = 1; optind < argc; optind++)
147 ok &= sum_func(argv[optind], 1);
149 if (have_read_stdin && fclose(stdin) == EOF)
150 bb_perror_msg_and_die("-");
152 exit(ok ? EXIT_SUCCESS : EXIT_FAILURE);