Counting the Number of Lines in File

Dave Sinkula 0 Tallied Votes 168 Views Share

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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.