#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2002
    Posts
    32
    Rep Power
    13

    C question: removing trailing newline


    how do you remove the trailing newline character from the end of each line (gotten from a call to fgets())?

    do i have to go so far as to detect a '\n' character by checking each character?

    thanks again!
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,615
    Rep Power
    4247
    Yep, that would be the best way to do it. The thing to realize about fgets() is that it will read upto (size -1) characters into the *str array.
    char * fgets(char *str, int size, FILE *stream);

    If it encounters a newline (\n) or end of file or error BEFORE it reaches (size - 1) characters, then it stops reading any more characters and returns. However, you don't know immediately after the fgets() call, whether it stopped on reading (size-1) characters, \n, EOF or error. You have to determine the result (at least EOF and error conditions) by calling other functions or errno var. The only way you can check if there is a \n in *str is by going through it, to see if there is one present.

    (Edit: Fixed size to size - 1)

IMN logo majestic logo threadwatch logo seochat tools logo