سؤال

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.

نصائح أخرى

temp_string is your buffer, i guess it is pre-allocated or on the stack so it cannot be NULL. It means that the inner loop will never stop.

You have to check the return code of the internal fgets()

Thanks for all the input. It was pointed out that in the inner while loop

while(j!=0 && temp_string != NULL){

the temp_string != NULL was never found. changing this to

!feof(inFile)

fixed the problem.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top