reading arbitrarily long strings from stdin
J. Greg Davidson
davidson at sdcsvax.UUCP
Mon Dec 30 08:43:32 AEST 1985
Sundar R. Iyengar says that my readline procedure can't really read
arbitrarily long strings because its recursive and will eventually run
out of stack space. Well now, arbitrarily long, in computer terms,
simply means that the length is limited by available memory, not by the
way the program is written.
However, I expected someone to complain about the space efficiency of
my first implementation. Very well, here is a second implementation in
which the recursion overhead can be made arbitrarily small (there's
that word again). I still prefer the original implementation for most
purposes.
#include <stdio.h>
#define BufSiz 32
char *
readline( fd )
FILE *fd;
/* Reads the next line ending in '\n' or EOF from fd.
Stores it, NUL terminated, into a malloc'ed string array.
Returns the address of the string. - greg at vis.UUCP
( J. Greg Davidson Virtual Infinity Systems, San Diego )
*/
{
char *rdln2( );
return rdln2( fd, (unsigned) 1);
}
static char *
rdln2( fd, l )
FILE *fd;
unsigned l;
/* See readline. Call with l == 1. */
{
char buf[BufSiz], *p = buf, *strp;
int c;
char *malloc();
while ( p < buf + BufSiz && (c = getc( fd )) != '\n' && c != EOF )
*p++ = c;
l += p - buf;
if ( c == '\n' || c == EOF )
{
strp = malloc( l ) + l;
*--strp = '\0';
}
else
strp = rdln2( fd, l );
while ( p > buf )
*--strp = *--p;
return strp;
}
/*
J. Greg Davidson Virtual Infinity Systems
(619) 452-8059 6231 Branting St; San Diego, CA 92122
greg at vis.uucp ucbvax--| telesoft--|
davidson at sdcsvax.uucp decvax--+--sdcsvax--+--vis
davidson at ucsd.arpa ihnp4--| noscvax--|
*/
More information about the Comp.sources.unix
mailing list