Search code examples
cfileparsingloopsfgetc

issue fgetc() c using while loop


I got a big problem using fgetc() and i can't figure it out... I try to parse a text file, everything compile but at the execution I got an infinite loop or a segfault (Code::blocks), my text file is like that: {"USD_EUR": "0.8631364", "EUR_USD": "1.3964719"} with 16 rates change. I try to put all my float in rate[16]...

FILE* file = NULL;
file = fopen(myFile, "r+");
int value,i;
float rate[16];
char* str = "";
if (file != NULL)
{
    do
    {
        value = fgetc(file);
        printf("%c \n",value);
        while(value > 48 && value < 57)
        {
            value = fgetc(file);
            strcat(str, value);
            //printf("%s \n", str);
        }
        rate[i] = atof(str);
        i++;
        str = "";
    }while(value != 125); // 125 = }

Solution

  • while(value =! EOF); should be while(value != EOF);

    It's a big difference. First case is an assignment to the variable value, second case looks if value is not equal to EOF.

    EOF is a macro and usually have the value -1, that means that !EOF becomes 0. Since you have a do{} while() it will run once but not more since condition is false.