On Thu, 10 Feb 2011 19:48:18 +0000, Gand Alf wrote:
> I have been writing a getline-type function. It should read an
> arbitrary length line from a file and return it in a buffer.
[snip #includes]
> void
> GL (char **buf, size_t * sz, FILE * fp) {
> size_t off = 0;
> char *new;
> for(;;)
What, you can't spell 'while' ?
> {
> if(*buf)
> {
> fgets (*buf + off, *sz - off, fp);
> if(strchr (*buf + off, '\n'))
> break;
> off += *sz - 1;
^ You have an extra character there.
> }
[snip realloc & most of main]
Note, your main starts off properly enough with
"int main (void)", but at the end has no "return 0".
> However when I run this with the following test file as input: ==begin
> input==
> hello
> world
> everyone
>
> bye
> ==end input==
> the results are as follows:
>
> 3
> 6
> 9
> 1
> 4
> 4
>
> instead I would expect to get:
> 5
> 5
> 8
> 0
> 3
>
> Can anyone see what the problem is?
(a) Wrong expectation -- Per man fgets, "If a newline is read,
it is stored into the buffer", and (eg) strlen("world\n") is 6.
(b) Mishandled EOF test -- Again per man, "fgets() returns ...
NULL ... when end of file occurs while no characters have been
read", but you've discarded the value of fgets(), so can't put
a \0 at **buf, etc
--
jiw