Yet another fgetline()
Garrett Wollman
wollman at emily.uvm.edu
Mon Feb 11 13:58:14 AEST 1991
Well, here is my version of the get-an-indefinite-length-string
routine. I call it frgets, and it acts very much like gets(). I uses
malloc to get memory. [Please note that I don't claim that it's at
all efficient, but it makes the most sense to me. PErhaps a good
compiler can make something of it.]
#include <stdio.h>
static char *frgets_h(FILE *fp,int accum) {
int c = fgetc(fp);
char *retval;
if((c == EOF)||(c == '\n')) {
retval = malloc(accum+1);
if(retval)
retval[accum] = '\0';
return(retval);
}
/* we didn't get an EOF or newline */
retval = frgets_h(fp,accum+1);
if(retval)
retval[accum] = (char)c; /* this may need fudging for signed chars < 0 */
return(retval);
}
char *frgets(FILE *fp) {
return(frgets_h(fp,0));
}
----------
Note that, if there is not enough memory available deep in the
recursion, then you lose all those characters that were read it. Too
bad. I think that if you can't malloc enough for a simple string,
that's probably the worst of your problems. No doubt all the other
readers of comp.lang.c will come down from on high and condemn this.
That's too bad too.
-GAWollman
Garrett A. Wollman - wollman at emily.uvm.edu
Disclaimer: I'm not even sure this represents *my* opinion, never
mind UVM's, EMBA's, EMBA-CF's, or indeed anyone else's.
More information about the Comp.lang.c
mailing list