C getline() - how to deal with buffers / how to re

2019-01-01 12:00发布

问题:

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!

回答1:

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



回答2:

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



标签: c getline