[net.sources] reading arbitrarily long strings from stdin

sundar@cwruecmp.UUCP (Sundar R. Iyengar) (12/28/85)

>From: davidson@sdcsvax.UUCP (J. Greg Davidson)
>Subject: Re: Routine to read arbitrary lenght lines from a stdio file desc.

Since you are recursively calling the "rdln" routine for each
character, the length of a string you can read depends on the
recursion depth.  So the string cannot be "arbitrarily" long.
On our VAX11/780 running 4.2BSD, the length must be <= 13036
characters.  It runs out of stack space after these many calls.

sri

davidson@sdcsvax.UUCP (J. Greg Davidson) (12/30/85)

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@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--|
*/