As elia mentions in the comments, the best strategy is to read the whole line
and then parse it with sscanf.
char buffer[1024];
while(fgets(buffer, sizeof buffer, fp1))
{
if(sscanf(buffer,"%lf,%lf,%lf,%lf",&a,&b,&c,&d) != 4)
{
fprintf(stderr, "Invalid line format, ignoring\n");
continue;
}
printf("a: %lf, b: %lf, c: %ld, d: %lf\n", a, b, c, d);
}
Another option is to keep reading until \n:
while(1)
{
if(fscanf(fp1,"%lf,%lf,%lf,%lf",&a,&b,&c,&d) != 4)
{
fprintf(stderr, "Invalid line format, ignoring\n");
if(clear_line(fp1) == 0)
{
fprintf(stderr, "Cannot read from fp1 anymore\n");
break;
}
continue;
}
printf("a: %lf, b: %lf, c: %ld, d: %lf\n", a, b, c, d);
if(clear_line(fp1) == 0)
{
fprintf(stderr, "Cannot read from fp1 anymore\n");
break;
}
}
and clear_line looks like this:
int clear_line(FILE *fp)
{
if(fp == NULL)
return 0;
int c;
while((c = fgetc(fp)) != '\n' && c != EOF);
return c != EOF;
}