How to use fgets() and store every line of a file using an array of char pointers?

大城市里の小女人 提交于 2019-12-06 14:01:01

The function fgets doesn't allocate new memory. So in case of success eof == line - that's right, it returns what you passed. You are overwriting it every time.

Try:

while((eof = fgets(line, 101, cf)) != NULL){
    lines[i] = strdup(eof);
    i++;
}

Of course you must remember to free(lines[i]).

eof = fgets(line, 101, cf)
while(eof!=NULL)
{
    puts(eof);
    eof=fgets(line,101,cf);
    free(eof);
}

You should use getline(3), e.g.

char* myline = NULL;
size_t mylinesize = 0;
ssize_t mylinelen = 0;
while ((mylinelen = getline(&myline, &mylinesize, cf)) >= 0) {  
    lines[i++] = strdup(myline);
}
free (myline); 
myline = NULL;

and you should consider using readline(3) and the GNU readline library (GPL licensed) for interactive use.

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