Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check incomplete line in fgets()

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$ 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.

>Solution :

the entire line fits in the buffer; there is no more to read from the file.

So check that

if (length == 4 && (line[3] != '\n' || feof(stdin))) {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading