C fgets versus fgetc for reading line

后端 未结 5 2172
南笙
南笙 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:18

    I would allocate a large buffer and then use fgets, checking, reallocing and repeating if you haven't read to the end of the line.

    Each time you read (either via fgetc or fgets) you are making a system call which takes time, you want to minimize the number of times that happens, so calling fgets fewer times and iterating in memory is faster.

    If you are reading from a file, mmap()ing in the file is another option.

提交回复
热议问题