I have files with a single column full of numbers and I want to sum all the files. The problem is to be able to exit as soon as invalid data is found (as soon as fprintf
fails).
A first attempt using goto
(and inspired by this answer) is the following
while(1) {
sum_a = 0;
for(i=0 ; i<N ;i++){
if(fscanf(infiles[i], "%d\n", &a) != 1){
goto end; // yeah, I know...
}
sum_a += a;
}
printf("%d\n", sum_a); // Should NOT be read if anything failed before
}
end:
for(i=0 ; i<N ;i++)
fclose(infiles[i]);
I would glad to see a nicer solution (ie not using goto
and while(1)
!). I don't want to mess up with many flags set and unset in a dirty way.