G
Gand Alf
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)
{
size_t off = 0;
char *new;
for(;
{
if(*buf)
{
fgets (*buf + off, *sz - off, fp);
if(strchr (*buf + off, '\n'))
break;
off += *sz - 1;
}
else
*sz = 1;
new = realloc (*buf, *sz <<= 1);
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
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)
{
size_t off = 0;
char *new;
for(;
{
if(*buf)
{
fgets (*buf + off, *sz - off, fp);
if(strchr (*buf + off, '\n'))
break;
off += *sz - 1;
}
else
*sz = 1;
new = realloc (*buf, *sz <<= 1);
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