Working on (what should be) a simple project, taking the input from stdin and reformatting it to match the output specs. I’m just wanting to see what the experts here think of the following function that is supposed to skip k chars up to the end of the line, unless k < 0, where it will keep skipping chars until it reaches newline.
1 #include <stdio.h> 25 int skip(int count){ 26 int i; 27 int ch; 28 29 for(i = 0; count < 0 || i < count; i++){ 30 ch = fgetc(stdin); 31 if(ch == EOF){ 32 return -1; 33 } 34 if(ch == '\n'){ 35 return 0; 36 } 37 } 38 return 1; 39 }
(including the line numbers for reference purposes)
There’s nothing seriously wrong with this code. But to make this more robust, I would:
Save the value of
fgetc(stdin)to anintvariable, then test it to make sure it’s a blank usingisspace(), reporting an error if not. Use anintnot acharbecausefgetc()returnsEOFat end of file, which cannot fit inside achar.Another minor concern is that on modern filesystems, file sizes can be larger than
INT_MAX. Instead of ‘faking’ acountvalue ofINT_MAXwhenk< 0, I would change the loop test to test it explicitly.In summary, the main loop becomes: