waltermilner

Untitled

Apr 23rd, 2016
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.94 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <malloc.h>
  4.  
  5.  
  6. int main()
  7. {
  8.     const int BUFLENGTH=1024; // size of buffer
  9.     char * buffer = malloc(BUFLENGTH); // make the buffer
  10.     FILE * file;
  11.     file = fopen("data.txt", "r"); // open file to read
  12.     if (file==NULL) // could we find it?
  13.     {
  14.         printf("File open failed\n");
  15.         return(1);
  16.     }
  17.     int totalChars=0; // initialisation
  18.     int lines=0;
  19.     int lineLength;
  20.     do
  21.     {
  22.         fgets(buffer, BUFLENGTH, file); // read up to new line
  23.         printf("%s",buffer); // check for debugging
  24.         lineLength=strlen(buffer)-1; // fgets includes newline at end, so -1
  25.         lines++;
  26.         totalChars+=lineLength;
  27.     }
  28.     while (lineLength); // stop at blank line
  29.     fclose(file);
  30.     lines--; // ignore blank line
  31.     printf("%d characters in %d lines => average is %f chars per line\n",totalChars,lines, (double)totalChars/lines);
  32.     return 0;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment