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 
9 #include <stdlib.h>
10 #include <stdio.h>
11 
main(int argc,char ** argv)12 int main(int argc, char **argv) {
13   unsigned Count, NumLines, NumRead;
14   char Buffer[4096], *End;
15 
16   if (argc != 2) {
17     fprintf(stderr, "usage: %s <expected line count>\n", argv[0]);
18     return 2;
19   }
20 
21   Count = strtol(argv[1], &End, 10);
22   if (*End != '\0' && End != argv[1]) {
23     fprintf(stderr, "%s: invalid count argument '%s'\n", argv[0], argv[1]);
24     return 2;
25   }
26 
27   NumLines = 0;
28   do {
29     unsigned i;
30 
31     NumRead = fread(Buffer, 1, sizeof(Buffer), stdin);
32 
33     for (i = 0; i != NumRead; ++i)
34       if (Buffer[i] == '\n')
35         ++NumLines;
36   } while (NumRead == sizeof(Buffer));
37 
38   if (!feof(stdin)) {
39     fprintf(stderr, "%s: error reading stdin\n", argv[0]);
40     return 3;
41   }
42 
43   if (Count != NumLines) {
44     fprintf(stderr, "Expected %d lines, got %d.\n", Count, NumLines);
45     return 1;
46   }
47 
48   return 0;
49 }
50