Search code examples
csearchtextwhile-loopfgets

text word search inside a text file - C programming


I would like to search a text word inside a text file. However, the code does not execute isnide the while loop. what is wrong with fgets definition? how can I fix it? the program always prints "outside of while msg"

char repeated_data [10] = "0123456789";
char temp[512];
FILE * fp5 = fopen("/home/eagle/Desktop/temp.txt","r");
if(fp5 == NULL)
{
     perror("temp_network.txt open failed");
     exit(EXIT_FAILURE);
}

//search the text inside the temp.txt
while(fgets(temp, 512, fp5) != NULL) 
{
     printf("while msg\n");
     if((strstr(temp, repeated_data)) != NULL) 
     {
         discard_message=1;
         printf("msg is discarded msg\n");
     }
     printf("inside of while\n");
}
fclose(fp5);
printf("outside of while msg\n");

Solution

  • The flow seems correct, what you can still do to find the problem is check feof and ferror, as documented here:

    If an error occurs, a null pointer is returned. Use either ferror or feof to check whether an error happened or the End-of-File was reached.

    As a side note, this:

    char repeated_data [10] = "0123456789";
    

    should be

    char repeated_data [] = "0123456789";
    

    or

    char repeated_data [11] = "0123456789";
    

    You forgot the null terminator.