To detect it, I’ve seen the following if
condition:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
char line[5];
while(fgets(line, 5, stdin)){
int length = strlen(line);
if (length == 4 && line[3] != '\n') {
puts("line too long");
return 1;
}
}
puts("correct file");
return 0;
}
which works here:
$ cc test.c -o test
$ printf '012\n' | ./test
correct file
$ printf '012' | ./test
correct file
$ printf '0123\n' | ./test
line too long
but fails when the length is equal to the maximum and it doesn’t have a trailing newline:
$ printf '0123' | ./test
line too long
The detection was incorrect as the entire line fits in the buffer; there is no more to read from the file.
You need to sign in to view this answers