[net.sources] Routine to read arbitrary lenght lines from a stdio file desc.

jason@ucbopal.BERKELEY.EDU (Jason Venner) (12/24/85)

This routine takes a FILE* as it's sole argument,  and returns a pointer
to a null terminated string in malloced memory.
The string will be terminated be a '\n''\0' if there is a terminating
'\n' in the input,  or just by a '\0' if an 'EOF' was hit.

There should be no problem using this on other UNIX version,  but I don't know.
---Cut Here Checksum via sum.1 is '22377     2'----
#include	<stdio.h>

/*	This routine reads a line (of arbitrary length), up to a '\n' or 'EOF'
 *	and returns a pointer to the resulting null terminated string.
 *	The '\n' if found, is included in the returned string.
 */

#define	STRGROW	256

char	*
readline( fd )
FILE	*fd;
{

	int	c;
	unsigned	StrLen;
	unsigned	MemLen;
	char	*StrPtr;
	char*	realloc();
	
	StrPtr = (char*) 0;
	StrLen = 0;
	MemLen = STRGROW; 
	if( !(StrPtr = realloc( StrPtr, MemLen )) ) {
		return (char*) 0;
	}
	MemLen -= 1;					  /* Save constant -1's in while loop */
	while( (c = getc( fd )) != EOF ) {
		StrPtr[StrLen] = c;
		StrLen++;
		if( StrLen >= MemLen ) {
			MemLen += STRGROW;
			if( !(StrPtr = realloc( StrPtr, MemLen + 1)) ) {
				return (char*) 0;
			}
		}
		if( c == '\n' ) {
			break;
		}
	}
	if( StrLen == 0 ) {
		(void) free( StrPtr );
		return (char*) 0;
	}
	StrPtr[StrLen] = '\0';
										  /* Trim the string */
	if( !(StrPtr = realloc( StrPtr, StrLen + 1 )) ) {
		return (char*) 0;
	}
	return StrPtr;
}

#ifdef	TEST_READLINE
main( argc, argv )
int	argc;
char	**argv;
{
	char	*string;
	while( (string = readline( stdin )) ) {
		puts( string );
		(void) free( string );
	}
	exit( 0 );
}
#endif
---Cut here also----
jason@jade.berkeley.edu
{ihnp4,sun,dual,tektronix}!ucbvax!ucbjade!jason

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

#include <stdio.h>

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 *rdln();

  return rdln( fd, (unsigned) 1);
}

static char *
rdln( fd, l )
  FILE *fd;
  unsigned l;
/* See readline.  Call with l == 1. */
{
  int c;
  char *p;
  char *malloc();

  c = getc( fd );
  if (c == '\n' || c == EOF)
    {
      p = malloc( l ) + l;
      *--p = '\0';
    }
  else
    {
      p = rdln( fd, l + 1 );
      *--p = c;
    }
  return p;
}

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