file descriptor vs. file pointer closing

Richard A. O'Keefe ok at quintus.uucp
Sun Aug 14 12:20:46 AEST 1988


In article <1122 at ssc-bee.ssc-vax.UUCP> lee at ssc-vax.UUCP (Lee Carver) writes:
>Why should file descriptor closing neccesarily close the file
>pointer?  Especially when there is more than one file descriptor
>associated with the file pointer.>Typical usage might be:
>   # this file is 'demo'
>   set src=`readtkn 'Enter source file > ' opt opt opt`
>   set dst=`readtkn 'Enter destination > ' opt opt opt`
>   cp $src $dst
>
>   # this file is 'test'
>   demo << EOF
>   model
>   /tmp/model
>   EOF
>   diff model /tmp/model
>The second execution of readtkn finds an end of file.

The problem isn't what you think it is.  It's actually quite simple.

Your program probably uses stdio.  By default, stdio is LINE buffered
when reading from terminals and BLOCK buffered when reading from
other devices.  Your program presumably calls fgets() or getc() to
read the response, but stdio will actually grab as much as it can get.
So when you run demo with a "here" file, the very first 'readtkn' is
asking for BUFSIZ characters (might be 512, or 1024, might even be more)
and is thus getting ALL of the "here" file.  The second execution of
'readtkn' is getting an end of file indication because the first one
really did eat all the characters.

The remedy is simple.  Only your program needs to change.
Before reading from stdin, do
	setbuf(stdin, (char*)NULL);	/* all flavours */
or	setlinebuf(stdin);		/* BSD */
or use setvbuf in System V.



More information about the Comp.unix.wizards mailing list