程序未检测到EOF。 程序计算“玻璃门”进入文件的次数。 它检测到其他字符,单词和行尾,并正确到达文件末尾,但随后没有进入检测EOF的条件,而是无限循环地反复读取并开始最后一行,并且永不退出。
#include <stdio.h>
// #include <conio.h> - Does not exist in gcc
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 256
#define MAX_WORD_SIZE 64
int main ()
{
// Declare file *
FILE* fp;
// Get file path and open file
//fp = fopen ("file_name.txt","r");
fopen_s(&fp, "file_name.txt", "r");
// Declare variables for line and word
char *line, *word;
line = (char*) malloc (MAX_LINE_LENGTH);
word = (char*) malloc (MAX_WORD_SIZE);
// Declare and initiaize count
unsigned int count = 0;
unsigned int i;
int j;
//Read a line till EOF is met
while (1)
{
fgets(line, MAX_LINE_LENGTH, fp );
i = 0, j = 0;
//for ( i=0, j=0; i<MAX_LINE_LENGTH; i++, j++)
while (*(line+i) != '\n')
{
// Extract word
if ( *(line+i) == EOF)
{
printf ("The file has \"Glassdoor\" %u times", count);
getchar();
return 0; // exit();
}
else if ( (*(line+i) == ' '))
{
// NUll terminate the word to make it a string
*(word+j) = '\0';
// Compare
if (strcmp (word, "Glassdoor") == 0)
count ++;
// Make j = -1, after increment it will be 0 for new word
j = -1;
}
else
{
*(word+j) = *(line+i);
}
// Increment both i and j to go to next character
i++; j++;
}
// If end of line - do the same thing on last word as is for every word
// NUll terminate the word to make it a string
*(word + j) = '\0';
// Compare
if (strcmp(word, "Glassdoor") == 0)
count++;
// Make j = -1, after increment it will be 0 for new word
//j = -1;
if (strcmp(word, "lastword") == 0)
{
//only for debugging
printf("Reached last word \n");
}
}
return -1; // Error - it should not reach here and exit this way
}