C getline() - how to deal with buffers / how to read unknown number of values into array
Solution 1:
This is not the correct use of getline
. I strongly suggest to read carefully its man page.
You could have some code like
FILE *inputfile=fopen("yourinput.txt", "r");
size_t linesiz=0;
char* linebuf=0;
ssize_t linelen=0;
while ((linelen=getline(&linebuf, &linesiz, inputfile)>0) {
process_line(linebuf, linesiz);
// etc
free(linebuf);
linebuf=NULL;
}
BTW, you might (and probably should better) put
free(linebuf);
linebuf=NULL;
... after the while
loop (to keep the line buffer allocated from one line to the next), and in most cases it is preferable to do so (to avoid too frequent malloc
-s from getline
).
Notice that getline
is in ISO/IEC TR 24731-2:2010 extension (see n1248).
Solution 2:
The buffer will only contain the last line you read with getline
. The purpose is just to take a little bit of the effort of managing memory off your code.
What will happen if you repeatedly call getline
, passing it the same buffer repeatedly, is that the buffer will expand to the length of the longest line in your file and stay there. Each call will replace its contents with the next line's.
You're not providing it a size_t*
, you're giving it a char*
.