Retiring gets

eao at zeus.umu.se eao at zeus.umu.se
Sat Dec 3 06:20:09 AEST 1988


When I retire gets() I would like a function like this fgetline() to replace
it. Are there any drawbacks I have missed? or is recursion to simple to use
in problems like this? (To parse a input in search of newline.)

/*
 * char *fgetline(file) 
 *	FILE *file;
 * returns a null terminated line from stdin allocated with *some_malloc
 */

#include <stdio.h>

/*
 * Size of chunks read whith fgets. This constant could be freely altered 
 * to achieve optimal efficiency. (Try 1 :-)
 */
#define BUFFSIZE 512

static char *head, *tail; 
static long size;
static FILE *stream;

void storetail(buff, tailsize)
	char *buff;
	long tailsize;
{
long headsize;
extern char *(*some_malloc)();
headsize = size;
size += tailsize;
head = (*some_malloc)(size + 1);
tail = head + headsize;
strncpy(tail,buff, tailsize);
return;
}

static void getchunk()
{
char buff[BUFFSIZE+1], *strchr();
static char *s;
s = fgets(buff, BUFFSIZE+1, stream);
if (s == NULL) 
	if (size == 0)
		/* Do nothing */;
	else
		storetail(buff, 0);
else 	{
	s = strchr(buff, '\n');
	if (s != NULL) { /* Newline has been read */
		*s = 0;
		storetail(buff, s - buff);
		}
	else { /* Newline is still to be seen. Read more */
		size += BUFFSIZE;
		getchunk();
		tail -= BUFFSIZE;
		strncpy(tail, buff, BUFFSIZE);
		}
	}
return;
}

char *fgetline(file)
	FILE *file;
{
size = 0;
stream = file;
getchunk();
if (size == 0)
	return NULL;
else	{
	head[size] = 0;
	return head;
	}
}

Erik Marklund	+90-16 63 30	



More information about the Comp.lang.c mailing list