cksum: ARGBEGIN, no buffering

This commit is contained in:
Connor Lane Smith 2012-05-14 21:30:02 +01:00
parent 146cca114e
commit f3188246d8
1 changed files with 30 additions and 20 deletions

50
cksum.c
View File

@ -1,10 +1,13 @@
/* See LICENSE file for copyright and license details. */ /* See LICENSE file for copyright and license details. */
#include <fcntl.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h> #include <unistd.h>
#include "util.h" #include "util.h"
static void cksum(FILE *, const char *); #define USAGE() usage("[files...]")
static void cksum(int, const char *);
static const unsigned long crctab[] = { 0x00000000, static const unsigned long crctab[] = { 0x00000000,
0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b,
@ -63,35 +66,42 @@ static const unsigned long crctab[] = { 0x00000000,
int int
main(int argc, char *argv[]) main(int argc, char *argv[])
{ {
FILE *fp; int i, fd;
if(getopt(argc, argv, "") != -1) ARGBEGIN {
exit(EXIT_FAILURE); default:
if(optind == argc) USAGE();
cksum(stdin, NULL); } ARGEND;
else for(; optind < argc; optind++) {
if(!(fp = fopen(argv[optind], "r"))) if(argc == 0)
eprintf("fopen %s:", argv[optind]); cksum(STDIN_FILENO, NULL);
cksum(fp, argv[optind]); else for(i = 0; i < argc; i++) {
fclose(fp); if((fd = open(argv[i], O_RDONLY)) == -1)
eprintf("open %s:", argv[i]);
cksum(fd, argv[i]);
close(fd);
} }
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
void void
cksum(FILE *fp, const char *s) cksum(int fd, const char *s)
{ {
int c; unsigned char buf[BUFSIZ];
unsigned long i, n, ck = 0; unsigned int ck = 0;
size_t len;
int i, n;
for(n = 0; (c = getc(fp)) != EOF; n++) for(len = 0; (n = read(fd, buf, sizeof buf)) > 0; len += n)
ck = (ck << 8) ^ crctab[(ck >> 24) ^ c]; for(i = 0; i < n; i++)
for(i = n; i > 0; i >>= 8) ck = (ck << 8) ^ crctab[(ck >> 24) ^ buf[i]];
ck = (ck << 8) ^ crctab[(ck >> 24) ^ (i & 0377)]; if(n < 0)
if(ferror(fp))
eprintf("%s: read error:", s ? s : "<stdin>"); eprintf("%s: read error:", s ? s : "<stdin>");
printf("%lu %lu", ~ck, n); for(i = len; i > 0; i >>= 8)
ck = (ck << 8) ^ crctab[(ck >> 24) ^ (i & 0xFF)];
printf("%u %lu", ~ck, len);
if(s != NULL) if(s != NULL)
printf(" %s", s); printf(" %s", s);
putchar('\n'); putchar('\n');