diff options
-rw-r--r-- | sum.c | 59 |
1 files changed, 23 insertions, 36 deletions
@@ -29,57 +29,44 @@ #define UINT16_BIT (16) #define BLOCK_SIZE (512) -struct sum { - uintmax_t size; - uintmax_t sum; -}; - -static struct sum sum_obsolete(FILE *f, int alt) +static int sum(const char *path, int alt) { - struct sum sum = { 0 }; + FILE *f = stdin; + if (path && strcmp(path, "-")) { + f = fopen(path, "rb"); + } + + if (f == NULL) { + fprintf(stderr, "sum: %s: %s\n", path, strerror(errno)); + return 1; + } int c; + uintmax_t size = 0; + uintmax_t sum = 0; + while ((c = fgetc(f)) != EOF) { - sum.size++; + size++; if (alt) { - sum.sum = (sum.sum >> 1) + - ((sum.sum & 1) << (UINT16_BIT - 1)); + sum = (sum >> 1) + ((sum & 1) << (UINT16_BIT - 1)); } - sum.sum += c; + sum += c; if (alt) { - sum.sum &= UINT16_MAX; + sum &= UINT16_MAX; } } - sum.sum = (sum.sum & UINT16_MAX) + (sum.sum >> UINT16_BIT); + sum = (sum & UINT16_MAX) + (sum >> UINT16_BIT); - /* obsolete sum program prints number of 512 byte blocks */ - if (sum.size % BLOCK_SIZE != 0) { - sum.size += BLOCK_SIZE; + if (size % BLOCK_SIZE != 0) { + size += BLOCK_SIZE; } - sum.size /= BLOCK_SIZE; - - return sum; -} - -static int cksum(const char *path, int alt) -{ - FILE *f = stdin; - if (path && strcmp(path, "-")) { - f = fopen(path, "rb"); - } - - if (f == NULL) { - fprintf(stderr, "sum: %s: %s\n", path, strerror(errno)); - return 1; - } - - struct sum sum = sum_obsolete(f, alt); + size /= BLOCK_SIZE; - printf("%"PRIuMAX" %"PRIuMAX"", sum.sum, sum.size); + printf("%ju %ju", sum, size); if (f != stdin) { printf(" %s", path); @@ -112,7 +99,7 @@ int main(int argc, char *argv[]) int r = 0; do { - r |= cksum(argv[optind++], alt); + r |= sum(argv[optind++], alt); } while (optind < argc); return r; } |