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

心不动则不痛 提交于 2019-11-25 22:54:05

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

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

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