How read a line of a file from C-shell?

Geoff Clare gwc at root.co.uk
Sat Nov 3 01:44:30 AEST 1990


In <1990Oct31.232525.7990 at diku.dk> kimcm at diku.dk (Kim Christian Madsen) writes:

>----------line.c-----Public Domain Version---------------
>#include <stdio.h>

>main()
>{
>	char	line[BUFSIZ];

>	fgets(line,BUFSIZ,stdin);
>	fputs(line,stdout);
>}
>----------------------------------------------------------

I was expecting to see a flood of followups pointing out the mistakes
in this implementation of "line".  None have appeared here so far, so
here goes.

The whole point of "line" is that it consumes just the one line of input,
leaving the rest for some other program (or another "line" command) to
read.  The version above, when used to read a regular file, will consume
one block of input, and throw away all but the first line.

It could be made to work correctly by using setvbuf() (if your system has
it) to set stdin to be line buffered, but then you still have the problem
of the line length limit of BUFSIZ bytes.  To cure that you would have to
loop until fgets() returns a buffer with a '\n' on the end.  And I haven't
even mentioned the lack of error checking yet.

There's a long way to go before you have a good quality implementation.
-- 
Geoff Clare <gwc at root.co.uk>  (Dumb American mailers: ...!uunet!root.co.uk!gwc)
UniSoft Limited, Hayne Street, London EC1A 9HH, England.   Tel: +44-71-315-6600



More information about the Comp.unix.questions mailing list