C fgets versus fgetc for reading line

后端 未结 5 2174
南笙
南笙 2020-12-30 09:05

I need to read a line of text (terminated by a newline) without making assumptions about the length. So I now face to possibilities:

  • Use fgets and
5条回答
  •  春和景丽
    2020-12-30 09:30

    Does your environment provide the getline(3) function? If so, I'd say go for that.

    The big advantage I see is that it allocates the buffer itself (if you want), and will realloc() the buffer you pass in if it's too small. (So this means you need to pass in something gotten from malloc()).

    This gets rid of some of the pain of fgets/fgetc, and you can hope that whoever wrote the C library that implements it took care of making it efficient.

    Bonus: the man page on Linux has a nice example of how to use it in an efficient manner.

提交回复
热议问题