cksum.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. while ((bytes_read = fread(bb_common_bufsiz1, 1, BUFSIZ, fp)) > 0) {
  24. cp = bb_common_bufsiz1;
  25. length += bytes_read;
  26. while (bytes_read--)
  27. crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ (*cp++)) & 0xffL];
  28. }
  29. filesize = length;
  30. for (; length; length >>= 8)
  31. crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ length) & 0xffL];
  32. crc ^= 0xffffffffL;
  33. if (inp_stdin) {
  34. printf("%" PRIu32 " %li\n", crc, filesize);
  35. break;
  36. }
  37. printf("%" PRIu32 " %li %s\n", crc, filesize, *argv);
  38. fclose(fp);
  39. } while (*(argv + 1));
  40. fflush_stdout_and_exit(EXIT_SUCCESS);
  41. }