cksum.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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) MAIN_EXTERNALLY_VISIBLE;
  10. int cksum_main(int argc UNUSED_PARAM, char **argv)
  11. {
  12. uint32_t *crc32_table = crc32_filltable(NULL, 1);
  13. uint32_t crc;
  14. long length, filesize;
  15. int bytes_read;
  16. uint8_t *cp;
  17. #if ENABLE_DESKTOP
  18. getopt32(argv, ""); /* coreutils 6.9 compat */
  19. argv += optind;
  20. #else
  21. argv++;
  22. #endif
  23. do {
  24. int fd = open_or_warn_stdin(*argv ? *argv : bb_msg_standard_input);
  25. if (fd < 0)
  26. continue;
  27. crc = 0;
  28. length = 0;
  29. #define read_buf bb_common_bufsiz1
  30. while ((bytes_read = safe_read(fd, read_buf, sizeof(read_buf))) > 0) {
  31. cp = (uint8_t *) read_buf;
  32. length += bytes_read;
  33. do {
  34. crc = (crc << 8) ^ crc32_table[(crc >> 24) ^ *cp++];
  35. } while (--bytes_read);
  36. }
  37. close(fd);
  38. filesize = length;
  39. for (; length; length >>= 8)
  40. crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ length) & 0xff];
  41. crc ^= 0xffffffffL;
  42. printf((*argv ? "%" PRIu32 " %li %s\n" : "%" PRIu32 " %li\n"),
  43. crc, filesize, *argv);
  44. } while (*argv && *++argv);
  45. fflush_stdout_and_exit(EXIT_SUCCESS);
  46. }