Search code examples
cloopsfgetc

fgetc is not stopping my loop


int ch;
char Name1[24], Name2[24],*p1,*p2;  
while ((ch = fgetc(inz)) != EOF){

            fseek(inz, -1, SEEK_CUR);

        fgets(Name1, 24, inz);
        fgets(Name2, 24, inz);
        p1 = Name1;
        p2 = Name2;
        p1 += 3;
        p2 += 3;

        if (atoi(p1) > atoi(p2)){
            fseek(inz, -46, SEEK_CUR);              
            fputs(Name2, inz);              
            fputs(Name1, inz);              

        }
        fseek(inz, -23, SEEK_CUR);      
        i --;
    }

I have this code. inz is my file in r+ mod. and i want to compare each string to next one and sort them depend on the 4th character. the function is working but..its unstoppable it runs forever... **I have tried to change the int ch; to char too. Still didn't work, and feof didn't work.


Solution

  • There are several problems with your code:

    1) You're making the assumption that each line is at least 4 characters long (plus newline). If the line were smaller than 4 bytes you would not be sorting based on the string itself and may be sorting based on uninitialized memory.

    2) You said you want to compare each line based on the 4th character, but you're actually comparing it based on the string starting from the 4th character. You're converting it to integer, which means you're also assuming that the line contains an numeric value.

    3) You're assuming each string took up 24 bytes in the file. I guess you're assuming each string is 23 characters long plus a newline? Is this assumption valid? If lines can be shorter than 24 bytes then this code is incorrect:

    fseek(inz, -46, SEEK_CUR);              
    

    Instead you want to rewind back to the actual total length of both strings plus two newlines. Even if the strings are 23 bytes, you're not factoring in the newlines here, so you want to be rewinding -48 not -46.

    4) When writing the string back to the file you are using fputs which does not include the newline character.

    5) You're not really sorting the file, you're just going through one iteration of a bubble sort. You're reordering the current two lines based on a comparison, but that doesn't sort the entire file. So the logic of the sort is also wrong.

    It would be cleaner to read each line, stick it in an array, sort the array based on the criteria you mentioned, then write it back to the file.

    So aside from all that, why does the loop never end?

    The last line in your loop is this:

    fseek(inz, -23, SEEK_CUR);  
    

    This means it always goes back 23 bytes just before trying to get the next character (fgetc). You'll never see the EOF then.