Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.18 KB | None | 0 0
  1. /*count.c
  2. Author: Sam Dunne
  3. Description: Counts the number of characters, words and line in a file
  4. Date: 5/11/2010 */
  5.  
  6. /* Edited by Emil 5/11/2010 */
  7.  
  8. #include <stdio.h>
  9. #include <string.h>
  10.  
  11. /* These could just as well be declared inside main(), and that is what I would do */
  12. FILE *fp1;
  13. char fname[300];
  14. /* I also turned c into a char instead of an int */
  15. int lines, space;
  16. char c;
  17.  
  18. int main() /* int main(), main should always return int */
  19. {
  20.  
  21.     printf("Enter the name of the file to analysis. \n");
  22.     fgets(fname, sizeof(fname), stdin);  /* NEVER use gets() */
  23.     fname[strlen(fname)-1] = '\0'; /* Remove last \n, which fgets() kept */
  24.  
  25.     fp1 = fopen(fname, "r");
  26.  
  27.         if ( fp1 == NULL )
  28.             {
  29.             printf("Invalid file name. Please try again. \n");
  30.             }
  31.         else
  32.             {
  33.             printf("File opened successfully. \n");
  34.             c = getc (fp1);
  35.  
  36.                 while ( c != EOF )
  37.                     {
  38.                     if ( c == '\n')
  39.                         {
  40.                         c = lines;
  41.                         lines++;
  42.                         }
  43.  
  44.                     if (c == ' ')
  45.                         {
  46.                         c = space;
  47.                         space++;
  48.                         }
  49.                     c = getc (fp1); /* get a new char */
  50.                     }
  51.             }
  52.    
  53.     printf("The file contained the following >%d lines \n >%d spaces",lines, space);
  54.     fclose(fp1);
  55.                    
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement