1 /* cksum.c - produce crc32 checksum value for each input
3 * Copyright 2008 Rob Landley <rob@landley.net>
5 * See http://opengroup.org/onlinepubs/9699919799/utilities/cksum.html
7 USE_CKSUM(NEWTOY(cksum, "HIPLN", TOYFLAG_BIN))
13 usage: cksum [-IPLN] [file...]
15 For each file, output crc32 checksum value, length and name of file.
16 If no files listed, copy from stdin. Filename "-" is a synonym for stdin.
18 -H Hexadecimal checksum (defaults to decimal)
19 -L Little endian (defaults to big endian)
21 -I Skip post-inversion
22 -N Do not include length in CRC calculation
29 unsigned crc_table[256];
32 static unsigned cksum_be(unsigned crc, unsigned char c)
34 return (crc<<8)^TT.crc_table[(crc>>24)^c];
37 static unsigned cksum_le(unsigned crc, unsigned char c)
39 return TT.crc_table[(crc^c)&0xff] ^ (crc>>8);
42 static void do_cksum(int fd, char *name)
44 unsigned crc = (toys.optflags & FLAG_P) ? 0xffffffff : 0;
45 uint64_t llen = 0, llen2;
46 unsigned (*cksum)(unsigned crc, unsigned char c);
48 cksum = (toys.optflags & FLAG_L) ? cksum_le : cksum_be;
54 len = read(fd, toybuf, sizeof(toybuf));
55 if (len<0) perror_msg_raw(name);
59 for (i=0; i<len; i++) crc=cksum(crc, toybuf[i]);
65 if (!(toys.optflags & FLAG_N)) {
67 crc = cksum(crc, llen);
72 printf((toys.optflags & FLAG_H) ? "%x" : "%u",
73 (toys.optflags & FLAG_I) ? crc : ~crc);
74 printf(" %"PRIu64, llen2);
75 if (strcmp("-", name)) printf(" %s", name);
81 crc_init(TT.crc_table, toys.optflags & FLAG_L);
82 loopfiles(toys.optargs, do_cksum);