Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.3 4.3bsd-beta 6/6/85; site sdcsvax.UUCP Path: utzoo!watmath!clyde!burl!ulysses!gamma!epsilon!zeta!sabre!petrus!bellcore!decvax!ittatc!dcdwest!sdcsvax!davidson From: davidson@sdcsvax.UUCP (J. Greg Davidson) Newsgroups: net.sources Subject: Re: reading arbitrarily long strings from stdin Message-ID: <1265@sdcsvax.UUCP> Date: Sun, 29-Dec-85 17:43:32 EST Article-I.D.: sdcsvax.1265 Posted: Sun Dec 29 17:43:32 1985 Date-Received: Tue, 31-Dec-85 00:20:56 EST References: <1364@cwruecmp.UUCP> Reply-To: davidson@sdcsvax.UUCP (J. Greg Davidson) Organization: EECS Dept. U.C. San Diego Lines: 64 Summary: Tuned readline for small stacks or slow function calls. 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 #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@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@vis.uucp ucbvax--| telesoft--| davidson@sdcsvax.uucp decvax--+--sdcsvax--+--vis davidson@ucsd.arpa ihnp4--| noscvax--| */