0

I am looking for an effective way to get the number of lines in a fie. I have the option of writing the number into another file after writing the file or opening the file and counting the lines. Which is better?

Mutai Mwiti
  • 487
  • 1
  • 7
  • 20
  • 3
    Count the number of `'\n'` characters. – alex May 25 '15 at 07:03
  • 2
    Most of the time keeping count of lines in another file along with date time of file would be faster. If the count file is not available or date/time of original file has changed, open the original file and count the number of new line characters. – Mohit Jain May 25 '15 at 07:04
  • 1
    Storing the line count in another file has the disadvantage that the count could possibly get out of sync with the file its supposed to describe. If this is going to be used in production, those kinds of issues nearly always cause headaches. Avoid that solution unless reading the file to get the count really has a undesirable performance impact. For example - do you have to read the file anyway? If so, then just read the file to get the line count. – Michael Burr May 25 '15 at 07:43

1 Answers1

0

This small program counts the line in a file and print the result:

#include <stdio.h>

int main() {

  FILE *fp;
  fp=fopen("./countLines.c", "r");
  long int lines =0;

  if ( fp == NULL ) {
    return -1;
  }

  while (EOF != (fscanf(fp, "%*[^\n]"), fscanf(fp,"%*c")))
        ++lines;

  printf("Lines : %li\n", lines);

  return 0;
}

The advantage of this solution is that we don't need to load the file in memory. We use scanf to match the \n line character.

This works only Linux/Mac if you want to make it work on Windows as well, you need to use \r\n instead of \n in the scanf function.

Giuseppe Pes
  • 7,772
  • 3
  • 52
  • 90