What is the fastest way to count lines and words in a text file in ANSI C?

前端 未结 3 1558
甜味超标
甜味超标 2020-12-04 03:29

What is the fastest way to count lines and words in a text file in pure ANSI C?

A word is terminated by a space or period. Line is terminated by \'\\n\'

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 03:46

    Here is an explicit answer that counts the number of lines (extension to the number of words is trivial à la the C++ version linked to in OP). This version is buffered. Another answer suggests reading the entire file in first, which is simpler, but the below is more in line with what your C++ example does.

    #include 
    #include 
    
    #define BUFSIZE 1024
    
    int main(int argc, char** argv)
    {
      int newlines = 0;
      char buf[BUFSIZE];
      FILE* file;
    
      if (argc != 2)
        return 1;
    
      file = fopen(argv[1], "r");
      while (fgets(buf, BUFSIZE, file))
      {
        if (!(strlen(buf) == BUFSIZE-1 && buf[BUFSIZE-2] != '\n'))
          newlines++;
      }
    
      printf("Number of lines in %s: %d\n", argv[1], newlines);
    
      return 0;
    }
    

    The BUFSIZE macro can be tweaked to maximize performance (since you say you want the fastest way). 1024 is simply a guess. Another possibility is probably to read the file memory mapped, but I didn't try since mmap is not ANSI C.

提交回复
热议问题