count.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*===- count.c - The 'count' testing tool ---------------------------------===*\
  2. *
  3. * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. * See https://llvm.org/LICENSE.txt for license information.
  5. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. *
  7. \*===----------------------------------------------------------------------===*/
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. int main(int argc, char **argv) {
  11. unsigned Count, NumLines, NumRead;
  12. char Buffer[4096], *End;
  13. if (argc != 2) {
  14. fprintf(stderr, "usage: %s <expected line count>\n", argv[0]);
  15. return 2;
  16. }
  17. Count = strtol(argv[1], &End, 10);
  18. if (*End != '\0' && End != argv[1]) {
  19. fprintf(stderr, "%s: invalid count argument '%s'\n", argv[0], argv[1]);
  20. return 2;
  21. }
  22. NumLines = 0;
  23. do {
  24. unsigned i;
  25. NumRead = fread(Buffer, 1, sizeof(Buffer), stdin);
  26. for (i = 0; i != NumRead; ++i)
  27. if (Buffer[i] == '\n')
  28. ++NumLines;
  29. } while (NumRead == sizeof(Buffer));
  30. if (!feof(stdin)) {
  31. fprintf(stderr, "%s: error reading stdin\n", argv[0]);
  32. return 3;
  33. }
  34. if (Count != NumLines) {
  35. fprintf(stderr, "Expected %d lines, got %d.\n", Count, NumLines);
  36. return 1;
  37. }
  38. return 0;
  39. }