Start New Discussion within our Software Development Community

This snippet shows one way to count the number of lines in a file. It will count the last line of a file even if the last line does not end in a newline.

Usage:

C:\>linecnt linecnt.c
lines = 32
#include <stdio.h>

int main(int argc, const char *const *argv)
{
   if ( argc > 1 )
   {
      FILE *file = fopen(argv[1], "r"); /* Get filename from command line. */
      if ( file )
      {
         int ch, prev = '\n' /* so empty files have no lines */, lines = 0;
         while ( (ch = fgetc(file)) != EOF ) /* Read all chars in the file. */
         {
            if ( ch == '\n' )
            {
               ++lines; /* Bump the counter for every newline. */
            }
            prev = ch; /* Keep a copy to later test whether... */
         }
         fclose(file);
         if ( prev != '\n' ) /* ...the last line did not end in a newline. */
         {
            ++lines; /* If so, add one more to the total. */
         }
         printf("lines = %d\n", lines);
      }
      else
      {
         perror(argv[1]);
      }
   }
   return 0;
}
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.