aboutsummaryrefslogtreecommitdiff
path: root/src/alfsum.c
blob: 7f30c7c905aec2a2bc4747e23e9a26ca4d2be084 (plain)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <unistd.h>

/* 20251104 bkw: implement the simple checksum used by ALF.
   Dumbest possible algo: all the bytes are added together and
   the bottom 16 bits of the result is the checksum. */

char *self;

void alfsum(const char *file, FILE *f) {
	int c;
	unsigned long sum = 0;

	while((c = fgetc(f)) != EOF)
		sum += c;

	printf("%8s\t%04x\n", file, (unsigned int)(sum & 0xffff));
}

int main(int argc, char **argv) {
	int errs = 0;
	char *file;
	FILE *f;

	self = argv[0];

	/* if the first arg is a - followed by anything at all, assume --help */
	if(argc < 2 || (argc == 2 && argv[1][0] == '-' && argv[1][1])) {
		fprintf(stderr,
				"usage: %s filename [filename ...]\n"
				"\t(use - to read from standard input)\n",
				self);
		return -1;
	}

	while((file = *++argv)) {
		if(argv[0][0] == '-' && !argv[0][1]) {
			if(isatty(0))
				fprintf(stderr, "%s: reading from stdin...\n", self);
			f = stdin;
			file = " (stdin)";
		} else if(!(f = fopen(file, "rb"))) {
			fprintf(stderr, "%s: ", self);
			perror(file);
			errs++;
			continue;
		}
		alfsum(file, f);
		fclose(f);
	}

	return errs > 254 ? 254 : errs;
}