Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <malloc.h>
- int main()
- {
- const int BUFLENGTH=1024; // size of buffer
- char * buffer = malloc(BUFLENGTH); // make the buffer
- FILE * file;
- file = fopen("data.txt", "r"); // open file to read
- if (file==NULL) // could we find it?
- {
- printf("File open failed\n");
- return(1);
- }
- int totalChars=0; // initialisation
- int lines=0;
- int lineLength;
- do
- {
- fgets(buffer, BUFLENGTH, file); // read up to new line
- printf("%s",buffer); // check for debugging
- lineLength=strlen(buffer)-1; // fgets includes newline at end, so -1
- lines++;
- totalChars+=lineLength;
- }
- while (lineLength); // stop at blank line
- fclose(file);
- lines--; // ignore blank line
- printf("%d characters in %d lines => average is %f chars per line\n",totalChars,lines, (double)totalChars/lines);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment