2 * cksum - report checksum and octet count of file(s)
5 * Build: c89 -o cksum cksum.c
6 * Source: <http://pdcore.sourceforge.net/>
7 * Spec: <http://www.opengroup.org/onlinepubs/9699919799/utilities/cksum.html>
9 * This is free and unencumbered software released into the public domain,
10 * provided "as is", without warranty of any kind, express or implied. See the
11 * file UNLICENSE and the website <http://unlicense.org> for further details.
23 #include <sys/types.h>
28 static void cksumfile(int fd, char *fn);
29 static void error(char *s);
31 static int exitstatus;
34 int main(int argc, char **argv)
36 int i, fd, hasrun = 0;
39 setlocale(LC_ALL, "");
41 for (i = 1; i < argc; i++)
45 if (strcmp(fn, "--") == 0)
51 if (strcmp(fn, "-") == 0)
52 cksumfile(STDIN_FILENO, "stdin");
54 if ((fd = open(fn, O_RDONLY)) == -1)
66 cksumfile(STDIN_FILENO, "stdin");
72 void cksumfile(int fd, char *fn)
74 unsigned char buf[BUFSIZE];
76 uint32_t crctab[256], crc, i;
79 for (i = 0; i < 256; ++i)
81 for (crc = i << 24, j = 0; j < 8; j++)
82 crc = (crc << 1) ^ (crc & 0x80000000 ? 0x04c11db7 : 0);
88 while ((n = read(fd, buf, BUFSIZE)) > 0)
92 for (i = 0; i < (size_t)n; i++)
93 crc = crctab[((crc >> 24) ^ buf[i]) & 0xFF] ^ (crc << 8);
100 for (i = cnt; i != 0; i >>= 8)
101 crc = crctab[((crc >> 24) ^ i) & 0xFF] ^ (crc << 8);
103 printf("%lu %lu", (unsigned long)~crc, (unsigned long)cnt);
104 if (fd != STDIN_FILENO)
113 fprintf(stderr, "cksum: %s: %s\n", s, strerror(errno));