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

青春壹個敷衍的年華 提交于 2019-11-26 01:47:47

问题


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



来源:https://stackoverflow.com/questions/9171472/c-getline-how-to-deal-with-buffers-how-to-read-unknown-number-of-values-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!