FILE I/O & SLOW WINDOWS

Alan J Rosenthal flaps at dgp.toronto.edu
Fri Feb 19 13:46:12 AEST 1988


In article <105 at richp1.UUCP> kk at richp1.UUCP writes:
>	buf[strlen(buf)-1] = '\0';	/* ZAP that newline */

aaackk!  if strlen(buf) == 0 (it would be on EOF in your original
example) then this will trash some random other variable.  the safe
way to write this is:

	if(buf[0])
	    buf[strlen(buf) - 1] = '\0';

Actually, though, in your original example if fgets() failed the first
time then buf[] might simply have garbage in it, so taking its strlen()
is not safe.  Test the fgets() return value.

Furthermore, the original use of this code was to remove a trailing
newline.  If EOF occurs in the middle of a line, it is inelegant to
throw away the last character of the file.

So the final version is:

	if(fgets(...) && buf[0] && buf[strlen(buf) - 1] == '\n')
	    buf[strlen(buf) - 1] = '\0';

ajr
-- 
"noalias considered sailaon"



More information about the Comp.lang.c mailing list