Program not detecting EOF. Program counts the number of times "Glassdoor" comes in a file. It detects other characters and words and end of line and reaches the end of file correctly, but then does not go into the condition to detect EOF, rather reads and starts the last line again and again in infinite loop and never exits.
#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
}