C - 获取文本文件行数的有效方法

C - Efficient way to get amount of lines of a text file

我刚刚发现 this 个有相同问题但使用 C# 的线程。
你如何在 C 中实现这一点?有没有比像这样使用循环直到达到 EOF 更好的解决方案,或者库中是否已经有一个函数可以做到这一点?

#include <stdio.h>
#include <stdlib.h>

// ----- Macros -----
#define PATHSIZE 255
#define BUFFERPATHSIZE PATHSIZE + 1

// ----- Functions -----
short get_amount_of_lines_of_file(char * path);

// -----======##### CODDE #####=====-----
int main() {

    char buffer[PATHSIZE];
    fgets(buffer, BUFFERPATHSIZE, stdin);

    printf("%d\n", get_amount_of_lines_of_file(buffer));

    return EXIT_SUCCESS;
}

short get_amount_of_lines_of_file(char * path) {
    /*
     * This will return the amount of lines of a file.
     * ----- Variables -----
     * lines: The counter of the lines
     * 
     * ----- Return -----
     * -1: Couldn't open file
     * lines: The amount of lines 
     */

    FILE *file;
    int rofl;
    short lines = 0;

    if ((file = fopen(path, "r")) != NULL) {

        while ((rofl = getc(file)) != EOF) 
            lines++;

        return lines;
    }

    return EXIT_FAILURE;
}

如果你想快点,如果你的内存足够大,你可以读入整个文件,并解析以获得换行数,试试这个:用gcc -g wc1.c -O3 -o wc1编译:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef __OSX__
   #define NLINE '\r'
#else
   #define NLINE '\n'
#endif
void main(int argn, char **argv){
  if(argn<2) return;
  FILE *fp=fopen(argv[1],"rb");
  int count=0;
  size_t flen;
  char *nb,*body;

  fseek(fp,0,SEEK_END);
  flen=ftell(fp);
  body=(char*)calloc(1,flen+1);
  fseek(fp,0,SEEK_SET);
  if(fread(body,flen,1,fp)!=1){
    fclose(fp);
    exit(-1);
  }
  fclose(fp);
  nb=body;
  while(nb=strchr(nb,NLINE)){
      count++;
      nb++;
  }
  free(body);
  printf("filename %s: line count %d\n",argv[1],count);
}

或者,您也可以设置最大行宽并调用 fgets 逐行读取,试试这个:gcc -g wc2.c -O3 -o wc2

#include <stdio.h>
#define MAX_LINE_LENGTH 4096

void main(int argn, char **argv){
  if(argn<2) return;
  FILE *fp=fopen(argv[1],"rt");
  int count=0;
  char line[MAX_LINE_LENGTH];
  while(!feof(fp)){
      if(fgets(line,MAX_LINE_LENGTH,fp))
         count++;
  }
  fclose(fp);
  printf("filename %s: line count %d\n",argv[1],count);
}