What is the easiest way to count the newlines in an ASCII file?

前端 未结 5 963
一生所求
一生所求 2020-11-30 10:01

Which is the fastest way to get the lines of an ASCII file?

5条回答
  •  星月不相逢
    2020-11-30 10:34

    Maybe I'm missing something, but why not simply:

    #include 
    int main(void) {
      int n = 0;
      int c;
      while ((c = getchar()) != EOF) {
        if (c == '\n')
          ++n;
      }
      printf("%d\n", n);
    }
    

    if you want to count partial lines (i.e. [^\n]EOF):

    #include 
    int main(void) {
      int n = 0;
      int pc = EOF;
      int c;
      while ((c = getchar()) != EOF) {
        if (c == '\n')
          ++n;
        pc = c;
      }
      if (pc != EOF && pc != '\n')
        ++n;
      printf("%d\n", n);
    }
    

提交回复
热议问题