cksum.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * cksum - calculate the CRC32 checksum of a file
  4. *
  5. * Copyright (C) 2006 by Rob Sullivan, with ideas from code by Walter Harms
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details. */
  8. #include "libbb.h"
  9. int cksum_main(int argc, char **argv);
  10. int cksum_main(int argc, char **argv)
  11. {
  12. uint32_t *crc32_table = crc32_filltable(NULL, 1);
  13. FILE *fp;
  14. uint32_t crc;
  15. long length, filesize;
  16. int bytes_read;
  17. char *cp;
  18. int inp_stdin = (argc == optind) ? 1 : 0;
  19. do {
  20. fp = fopen_or_warn_stdin((inp_stdin) ? bb_msg_standard_input : *++argv);
  21. crc = 0;
  22. length = 0;
  23. #define read_buf bb_common_bufsiz1
  24. while ((bytes_read = fread(read_buf, 1, BUFSIZ, fp)) > 0) {
  25. cp = read_buf;
  26. length += bytes_read;
  27. while (bytes_read--)
  28. crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ (*cp++)) & 0xffL];
  29. }
  30. filesize = length;
  31. for (; length; length >>= 8)
  32. crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ length) & 0xffL];
  33. crc ^= 0xffffffffL;
  34. if (inp_stdin) {
  35. printf("%" PRIu32 " %li\n", crc, filesize);
  36. break;
  37. }
  38. printf("%" PRIu32 " %li %s\n", crc, filesize, *argv);
  39. fclose(fp);
  40. } while (*(argv + 1));
  41. fflush_stdout_and_exit(EXIT_SUCCESS);
  42. }