Newsgroups: comp.lang.c
Path: utzoo!utgpu!jarvis.csri.toronto.edu!dgp.toronto.edu!flaps
From: flaps@dgp.toronto.edu (Alan J Rosenthal)
Subject: Re: FILE I/O & SLOW WINDOWS
Message-ID: <1988Feb18.224613.19694@jarvis.csri.toronto.edu>
Organization: University of Toronto
References: <11678@brl-adm.ARPA> <105@richp1.UUCP>
Date: Thu, 18-Feb-88 22:46:12 EST


In article <105@richp1.UUCP> kk@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"
