/* Name: readfile2.c Purpose: Similar to readfile1.c, but now process the file line by line Author: Bill Slough Bugs: 1. Doesn't count lines correctly. If an input line is too long, the character array is filled to capacity and the rest of the line is left for a subsequent read. 2. Words which do fit in the character array are terminated with newlines. This is a direct result of the way the fgets() function is designed. Still, you may not want these newlines! 3. fgets() returns NULL if one of two conditions exists: either a read error occurs or we have reached the end of the stream. Here, we assume no read error occurs and don't check for it. */ #include #include #include #define FILE_NAME "words" /* name of the input file */ #define MAX_WORD_LENGTH 8 int main(void) { FILE *fp; /* file pointer for an input stream */ int charCount; /* number of characters processed */ int lineCount; /* number of lines processed */ char line[MAX_WORD_LENGTH + 1]; /* string to hold one line of input */ /* Try to open the input stream for reading */ fp = fopen(FILE_NAME, "r"); if (fp == NULL) { fprintf(stderr, "Error: can't open %s for reading.\n", FILE_NAME); exit(EXIT_FAILURE); } /* process the file, line by line */ charCount = 0; lineCount = 0; while (fgets(line, sizeof(line), fp) != NULL) { printf("Current line = \"%s\"\n", line); charCount += strlen(line); lineCount++; } printf("Characters processed = %d\n", charCount); printf("Lines processed = %d\n", lineCount); /* close the stream */ fclose(fp); return 0; }