August 27th, 2002, 04:02 AM
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?
August 28th, 2002, 01:01 AM
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)