Does fgets(3) really work right?

Barry Margolin barmar at think.COM
Wed Mar 23 04:57:59 AEST 1988


In article <10900013 at bradley> brad at bradley.UUCP writes:
>
>A student here pointed this out to me,  is this a bug?  I checked
>it out on our 3B15 (V5), VAX 11/750 (4.3) and IBMPC (VENIX/86 2.0).
>
>you check the output,  should we not get 15 chars on the first
>line?  Mine prints the whole thing.
>
>========cut here for file named "in"=========
>12345678901234567890
>12345
>aaaaa
>========cut here for "temp.c"=============
>#include	<stdio.h>
>
>main()
>{
>	char str[15], *cp;
>	FILE *fp;
>
>	fp = fopen("in","r");
>	while((cp = fgets(str, 15, fp)) != NULL) 
>		printf("%s", str);
>	fclose(fp);
>	exit(0);
>}

Try

	printf("%s\n", str);

fgets doesn't automatically add a newline to the end if the input is
terminated because it reached your limit.  And printf doesn't output a
newline if you don't tell it to.  So, the results of the first two
fgets calls were being printed on the same line.

What I like to do when I am debugging things like this is to use more
obvious delimiters in my output, e.g.

	printf("|%s|", str);

As long as my test input doesn't contain any vertical bars, it will be
quite obvious where individual strings begin and end.  Using stuff
like this rather than newlines also results in less confusion about
how many newlines there are between things, or whether a particular
newline is at the end of one string or the beginning of the next one.

Barry Margolin
Thinking Machines Corp.

barmar at think.com
uunet!think!barmar



More information about the Comp.unix.wizards mailing list