C getline() - how to deal with buffers / how to read unknown number of values into array

theeggman85 picture theeggman85 · Feb 7, 2012 · Viewed 20.1k times · Source

First of all, some background: I'm trying to get in a list of integers from an external file and put them into an array. I am using getline to parse the input file line by line:

int lines = 0;
size_t * inputBuffer = (size_t *) malloc(sizeof(size_t));
char * storage = NULL;

I am calling getline like so:

getline(&storage, &s, input)

I heard from the man page on getline that if you provide a size_t * buffer, you can have getline resize it for you when it exceeds the byte allocation. My question is, what can you use this buffer for? Will it contain all of the items that you read with getline()? Is it simpler to read from this buffer, or to traverse the input in a different way when putting these integers into an array? Thanks!

Answer

Basile Starynkevitch picture Basile Starynkevitch · Feb 7, 2012

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).