xref: /illumos-gate/usr/src/ucbcmd/sum/sum.c (revision 8b6b46dcb073dba71917d6a7309f0df7bad798a2)
1 /*
2  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
7 /*	  All Rights Reserved  	*/
8 
9 
10 /*
11  * Copyright (c) 1980 Regents of the University of California.
12  * All rights reserved. The Berkeley software License Agreement
13  * specifies the terms and conditions for redistribution.
14  */
15 
16 /*
17  * Sum bytes in file mod 2^16
18  */
19 
20 #include <stdio.h>
21 
22 int
23 main(int argc, char **argv)
24 {
25 	unsigned int sum;
26 	int i, c;
27 	FILE *f;
28 	long long nbytes;
29 	int errflg = 0;
30 
31 	i = 1;
32 	do {
33 		if (i < argc) {
34 			if ((f = fopen(argv[i], "r")) == NULL) {
35 				(void) fprintf(stderr,
36 					"sum: Can't open %s\n", argv[i]);
37 				errflg += 10;
38 				continue;
39 			}
40 		} else
41 			f = stdin;
42 		sum = 0;
43 		nbytes = 0;
44 		while ((c = getc(f)) != EOF) {
45 			nbytes++;
46 			if (sum&01)
47 				sum = (sum>>1) + 0x8000;
48 			else
49 				sum >>= 1;
50 			sum += c;
51 			sum &= 0xFFFF;
52 		}
53 		if (ferror(f)) {
54 			errflg++;
55 			(void) fprintf(stderr,
56 				"sum: read error on %s\n",
57 				argc > 1 ? argv[i] : "-");
58 		}
59 
60 		(void) printf("%05u %5lld", sum,
61 			(nbytes + BUFSIZ - 1) / BUFSIZ);
62 		if (argc > 2)
63 			(void) printf(" %s", argv[i]);
64 		(void) printf("\n");
65 		(void) fclose(f);
66 	} while (++i < argc);
67 
68 	return (errflg);
69 }
70