Velocity Reviews > getline problem

# getline problem

Barry Schwarz
Guest
Posts: n/a

 02-24-2011
On Thu, 10 Feb 2011 19:48:18 +0000 (UTC), Gand Alf <(E-Mail Removed)>
wrote:

>Hello
>
>I have been writing a getline-type function. It should read an arbitrary
>length line from a file and return it in a buffer.
>
>Here is my code
>
>
>#include<stdio.h>
>#include<stdlib.h>
>#include<string.h>
>void
>GL (char **buf, size_t * sz, FILE * fp)

1 - The first time you call GL, *buf is NULL and *sz is 0
2 - The second time you call GL, *sz is 8 and buf points to an 8-byte
area.
3 - The third time you call GL is the same as the second.
4 - You should work out the fourth and subsequent iterations for
yourself.

>{
> size_t off = 0;
> char *new;
> for(;
> {
> if(*buf)
> {
> fgets (*buf + off, *sz - off, fp);

1B - On the second iteration, *buf points to "h\0".
1C - On the third iteration, *buf points to "hel\0".
1D - On the fourth iteration, *buf points to "hel\0lo\n\0" It should
now be obvious why your first output is 3.

2A - On the first iteration, *buf points to "world\n\0" . It should
now be obvious why your second output is 6.

3A - On the first iteration, *buf points to "everyon\0".
3B - On the second iteration, *buf points to "everyone\n\0". It
should be obvious why your third output is 9.

> if(strchr (*buf + off, '\n'))

> break;
> off += *sz - 1;

1B - off contains 1.
1C - off now contains 4.

3A - off now contains 7.

> }
> else

1A - You set *sz to 1 on the first iteration of the for loop.

> *sz = 1;
> new = realloc (*buf, *sz <<= 1);

1A - Ignoring malloc failures, *sz is now 2 and new points to a 2-byte
area.
1B - *sz is now 4 and new points to a 4-byte area.
1C - *sz is now 8 and new points to an 8-byte area.

3A = *sz is now 16 and new points to a 16 byte area.

> if(!new)
> {
> free (*buf);
> *buf = *sz = 0;
> return;
> }
> *buf = new;
> }
>}
>
>int
>main (void)
>{
> char *p = 0;
> size_t sz = 0;
> while(!feof (stdin))
> {
> GL (&p, &sz, stdin);
> printf ("%d\n", strlen (p));
> }
>}
>
>
>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?
>
>Thanks

--
Remove del for email