If I am using the fgets() function to search for a specific delimiter throughout a text file, how do I make sure the fgets() does not infinitely loop at the EOF?
I am concatenating all the lines from delimiter1 through delimiter2 into struct1[i].string1, where i is the nth occurrence of the delimiter1/delimiter2 pattern. This pattern continues throughout the text file until the very end, where instead of there being delimiter2, there is the EOF. I want to concatenate everything from delimiter1 to the EOF as well.
int i;
while(fgets(temp_string,100,inFile) != NULL){
if(strcmp(temp_string,"Delimiter1")==0){ //checks to see if current line is delimiter1
j=strcmp(temp_string,"Delimiter2");
while(j!=0 && temp_string != NULL){ //Here I try to exit if it is the EOF
fgets(temp_string,100,inFile);
strcat(struct1[i].string1,temp_string);
j= strcmp(temp_string,"Delimiter2"); //update comparator
}
i++;
}
}
}
However, when I try to run this code, I get stuck in an infinite loop. I put a print statement in the inner while loop showing what the integer "i" was, and it was stuck at the number 4, which is the total number of delimiter1's in the text file, leading me to believe the EOF is giving me the infinite loop.
Any help would be appreciated.
Reason for infinite loop is inner loop:
while(j!=0 && temp_string != NULL){ //Here
^ ^ never set to NULL
| never became 0 if "Delimiter2" not found
Suppose, if in temp_string value is not "Delimiter2"
then you never set to j
= 0 and also you don't set temp_string to NULL
You read in temp_string 100
char at once so "Delimiter2"
might be read from file with some other charters that is the reason strcmp() doesn't return 0 even on reading "Delimiter2"
.
Try to bug your code by printf you temp_string.
Also, you can use strstr()
function in place of strcmp()
to find "Delimiter2"
in your file. strstr()
return a valid address if "Delimiter2"
found any where in temp_string, other wise NULL.