Mail Archives: djgpp/2000/05/11/06:13:01
Thomas J. Hruska wrote:
>char *LineInput(FILE *fp)
>{
> char *str, x[2];
> str = (char *)malloc(1);
> str[0] = '\0';
> if (feof(fp)) return str;
> x[1] = '\0';
> do
> {
> x[0] = fgetc(fp);
> str = (char *)realloc(str, strlen(str) + 2);
> strcat(str, x);
> } while (!feof(fp) && x[0] != 10);
> if (x[0] != 10) return str;
> str[strlen(str) - 2] = '\0';
> str = (char *)realloc(str, strlen(str) + 1);
> return str;
>}
>
>Under any other compiler besides DJGPP, this works fine. Under DJGPP, the
>last line of ANY file will have an extra character on the end.
DJGPP seems correct from your description. From the comp.lang.c FAQ
12.2: Why does the code
while(!feof(infp)) {
fgets(buf, MAXLINE, infp);
fputs(buf, outfp);
}
copy the last line twice?
A: In C, end-of-file is only indicated *after* an input routine has
tried to read, and failed. (In other words, C's I/O is not like
Pascal's.) Usually, you should just check the return value of
the input routine (in this case, fgets() will return NULL on end-
of-file); often, you don't need to use feof() at all.
Also, I get the same behaviour with bcc 5.5 (and remember the same
behaviour back in Turbo-C 2.0).
> I do NOT
>relish the idea of modifying this ancient code (wrote it in early 1997) to
>include one more realloc.
It does already contain too many realloc calls, none of which tests
for NULL return. It uses unneeded calls to strlen and strcat. IHMO,
you should change your code.
#include <stdlib.h>
#include <stdio.h>
/* Untested, supplement with checking the return of malloc/realloc */
/* A different interface, that indicates EOF back to the caller, could
be more useful. */
char *LineInput(FILE *fp)
{
size_t nread, nalloc;
int c;
char *bp;
nalloc = 16;
nread = 0;
bp = malloc(nalloc);
while (1)
{
c = fgetc(fp);
if (c == EOF || c == '\n')
break;
bp[nread++] = c;
if (nread >= nalloc)
{
nalloc *= 2;
bp = realloc(bp, nalloc);
}
}
bp[nread] = '\0';
bp = realloc(bp, nread);
return bp;
}
> Make sure the next release of DJGPP fixes this bug.
From your description, I don't see anything that has to be fixed.
--
Dieter Buerssner
- Raw text -