best way to return (char *)

Bennett Todd bet at orion.mc.duke.edu
Wed Jul 12 16:15:31 AEST 1989


As has been said, in general the best mechanism to use depends on other
features of the problem at hand. Here's a specific solution that I liked
for a particular problem.

I wanted to be able to easily loop along line at a time through a file,
without having to worry about maximum line lengths. So I wrote a routine
getline(3b):

	char *getline(char *, FILE *);

which might be used like this:

	char *line = NULL;
	...
	while (line = getline(line, fp)) {
		/* process the line */
	}

getline(3b) allocates the line buffer if it is passed in NULL for a
buffer pointer; on EOF it frees the buffer and returns NULL. It actually
malloc's a 2^n byte long buffer, stores n in the first element, and the
string starting in the second element, and returns a pointer to the
second element. That way it knows the length, and can realloc as
necessary to avoid overfilling the buffer.

-Bennett
bet at orion.mc.duke.edu



More information about the Comp.lang.c mailing list