count.c 706 B

1234567891011121314151617181920212223242526272829
  1. /* count.c -- using standard I/O */
  2. #include <stdio.h>
  3. #include <stdlib.h> // exit() prototype
  4. int main(int argc, char *argv[])
  5. {
  6. int ch; // place to store each character as read
  7. FILE *fp; // "file pointer"
  8. unsigned long count = 0;
  9. if (argc != 2)
  10. {
  11. printf("Usage: %s filename\n", argv[0]);
  12. exit(EXIT_FAILURE);
  13. }
  14. if ((fp = fopen(argv[1], "r")) == NULL)
  15. {
  16. printf("Can't open %s\n", argv[1]);
  17. exit(EXIT_FAILURE);
  18. }
  19. while ((ch = getc(fp)) != EOF)
  20. {
  21. putc(ch,stdout); // same as putchar(ch);
  22. count++;
  23. }
  24. fclose(fp);
  25. printf("File %s has %lu characters\n", argv[1], count);
  26. return 0;
  27. }