xref: /titanic_41/usr/src/ucbcmd/sum/sum.c (revision 0adc16190e36914964740716575460dda750de39)
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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
17 
18 /*
19  * Sum bytes in file mod 2^16
20  */
21 
22 #include <stdio.h>
23 
24 int
25 main(int argc, char **argv)
26 {
27 	unsigned int sum;
28 	int i, c;
29 	FILE *f;
30 	long long nbytes;
31 	int errflg = 0;
32 
33 	i = 1;
34 	do {
35 		if (i < argc) {
36 			if ((f = fopen(argv[i], "r")) == NULL) {
37 				(void) fprintf(stderr,
38 					"sum: Can't open %s\n", argv[i]);
39 				errflg += 10;
40 				continue;
41 			}
42 		} else
43 			f = stdin;
44 		sum = 0;
45 		nbytes = 0;
46 		while ((c = getc(f)) != EOF) {
47 			nbytes++;
48 			if (sum&01)
49 				sum = (sum>>1) + 0x8000;
50 			else
51 				sum >>= 1;
52 			sum += c;
53 			sum &= 0xFFFF;
54 		}
55 		if (ferror(f)) {
56 			errflg++;
57 			(void) fprintf(stderr,
58 				"sum: read error on %s\n",
59 				argc > 1 ? argv[i] : "-");
60 		}
61 
62 		(void) printf("%05u %5lld", sum,
63 			(nbytes + BUFSIZ - 1) / BUFSIZ);
64 		if (argc > 2)
65 			(void) printf(" %s", argv[i]);
66 		(void) printf("\n");
67 		(void) fclose(f);
68 	} while (++i < argc);
69 
70 	return (errflg);
71 }
72