[comp.sys.atari.st] First Shot

ericco@stew.ssl.berkeley.edu (03/02/90)

OK, here's a tidbit of C code to get the ball rolling.  I've
never found a safe line general line reader.  This one mallocs
some space, which must later be free'd.

Eric


#define	READSIZE	256		/* any number you like	*/

char	*readline (in)
FILE	*in;				/* stream to read from	*/
{
static	unsigned long length = 0;	/* total length		*/
char	buffer[READSIZE];		/* temp stack space	*/
int	count;				/* current segment len	*/
char	*malloc();
char	*ret;				/* what to return	*/
					/* should be a better way*/

if (fgets (buffer, READSIZE, in))	/* safe but finite read	*/
  count = strlen(buffer);
else if (length == 0)			/* out of data		*/
  return NULL;

length += count;
/*
**	length != 0 count == 0 ==> out of data, but some read in.
**	count != 0 buffer[count-1] == \n ==> end of line
**		so I pick off the silly \n character.
*/
if (count == 0 || (buffer[count-1] == '\n' && (count--, length--, 1)))
  {
    ret = malloc (length+1);		/* one malloc per read	*/
    ret[length]='\0';			/* start at the end	*/
  }
else					/* more to come		*/
  ret = readline(in);			/* recurse		*/

if (ret && count)			/* got bytes to move	*/
  {
    length -= count;			/* move pointer back	*/
    bcopy (buffer, ret + length, count);/* move bytes		*/
  }
return ret;				/* unwind stack		*/
}
Eric
ericco@ssl.berkeley.edu