0
#include <stdio.h>

int main(int argc, char **argv) {

    FILE *file = fopen(argv[1], "r");
    char buf[100];
    while (fgets(buf, sizeof(buf), file)) {
        fprintf(stderr, "%s: unparseable line: '%s', ignored\n", argv[0], buf);

    }


}

I got this random bug in my code. Consider this file

echo 1
echo 2 
echo 3

If I were to do

$ gcc -Wall above.c
$ ./a.out file
./a.out: unparseable line: 'echo 1
', ignored
./a.out: unparseable line: 'echo 2
', ignored
./a.out: unparseable line: 'echo 3
', ignored

Why is the "', ignored" in it's own line? I want it to be 3 lines only not 6. Anyway to fix?

  • 1
    Because `fgets` retains the newline (if any). Please see [Removing trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input/28462221#28462221) – Weather Vane Mar 21 '18 at 07:42
  • 1
    A [good `fgets` reference](http://en.cppreference.com/w/c/io/fgets) should be useful to read. Just about *any* tutorial or book that uses `fgets` should have told you about the issue. – Some programmer dude Mar 21 '18 at 07:42

0 Answers0