xref: /original-bsd/usr.bin/cksum/cksum.c (revision 65d10654)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * James W. Williams of NASA Goddard Space Flight Center.
7  *
8  * %sccs.include.redist.c%
9  */
10 
11 #ifndef lint
12 static char copyright[] =
13 "@(#) Copyright (c) 1991, 1993\n\
14 	The Regents of the University of California.  All rights reserved.\n";
15 #endif /* not lint */
16 
17 #ifndef lint
18 static char sccsid[] = "@(#)cksum.c	8.2 (Berkeley) 04/28/95";
19 #endif /* not lint */
20 
21 #include <sys/cdefs.h>
22 #include <sys/types.h>
23 
24 #include <err.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 
32 #include "extern.h"
33 
34 void usage __P((void));
35 
36 int
37 main(argc, argv)
38 	int argc;
39 	char **argv;
40 {
41 	register int ch, fd, rval;
42 	u_long len, val;
43 	char *fn, *p;
44 	int (*cfncn) __P((int, unsigned long *, unsigned long *));
45 	void (*pfncn) __P((char *, unsigned long, unsigned long));
46 
47 	if ((p = rindex(argv[0], '/')) == NULL)
48 		p = argv[0];
49 	else
50 		++p;
51 	if (*p == 'c') {
52 		cfncn = crc;
53 		pfncn = pcrc;
54 	} else {
55 		cfncn = csum1;
56 		pfncn = psum1;
57 	}
58 
59 	while ((ch = getopt(argc, argv, "o:")) != -1)
60 		switch (ch) {
61 		case 'o':
62 			if (!strcmp(optarg, "1")) {
63 				cfncn = csum1;
64 				pfncn = psum1;
65 			} else if (!strcmp(optarg, "2")) {
66 				cfncn = csum2;
67 				pfncn = psum2;
68 			} else {
69 				warnx("illegal argument to -o option");
70 				usage();
71 			}
72 			break;
73 		case '?':
74 		default:
75 			usage();
76 		}
77 	argc -= optind;
78 	argv += optind;
79 
80 	fd = STDIN_FILENO;
81 	fn = NULL;
82 	rval = 0;
83 	do {
84 		if (*argv) {
85 			fn = *argv++;
86 			if ((fd = open(fn, O_RDONLY, 0)) < 0) {
87 				warn("%s", fn);
88 				rval = 1;
89 				continue;
90 			}
91 		}
92 		if (cfncn(fd, &val, &len)) {
93 			warn("%s", fn ? fn : "stdin");
94 			rval = 1;
95 		} else
96 			pfncn(fn, val, len);
97 		(void)close(fd);
98 	} while (*argv);
99 	exit(rval);
100 }
101 
102 void
103 usage()
104 {
105 	(void)fprintf(stderr, "usage: cksum [-o 1 | 2] [file ...]\n");
106 	exit(1);
107 }
108