user234159 user234159 - 2 months ago 7
C Question

Strange behavior in file reading in C

So I want to read some data from a csv file.

But fgets keeps giving me NULL in the while loop. It works fine outside the while loop.

Maybe I'm missing something obvious here.

Edit: I just cleaned up the code

int main(int argc, char *argv[])
{

FILE *input_file = fopen("free-zipcode-database-Primary.csv","r");
char buffer[1024];

if (input_file == 0) {
fprintf(stderr,"Cannot open input file.\n");
}



int count = 0; // to skip the first line in csv that contains the titles


while (1)
{


if (count == 0)
{
continue;
}

if (fgets(buffer, 1024, input_file) != NULL)
{
puts(buffer);
parseDataFromCSV(buffer);
} else {
break;
}




count++;

}


fclose(input_file);

return 0;
}


Edit: Here's the working code.

FILE *input_file = fopen("free-zipcode-database-Primary.csv","r");
char buffer[1024];

if (input_file == 0)
{
fprintf(stderr,"Cannot open input file.\n");
}

/* skip the first line in csv file */
fgets(buffer, 1024, input_file);
while (1)
{

if (fgets(buffer, 1024, input_file) != NULL)
{
puts(buffer);
parseDataFromCSV(buffer);
bzero(buffer,1024);
break;
} else {
break;
}


}


fclose(input_file);

Answer

You have infinite loop inside while loop.

if (count == 0) {
    continue;
}
Comments