C Program to Count the Number of Lines in Text File

This C Program displays the number of lines in a text file.

Here is source code of the C Program to find the number of lines in a text file. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Find the Number of Lines in a Text File
  3.  */
  4. #include <stdio.h>
  5.  
  6. int main()
  7. {
  8.     FILE *fileptr;
  9.     int count_lines = 0;
  10.     char filechar[40], chr;
  11.  
  12.     printf("Enter file name: ");
  13.     scanf("%s", filechar);
  14.     fileptr = fopen(filechar, "r");
  15.    //extract character from file and store in chr
  16.     chr = getc(fileptr);
  17.     while (chr != EOF)
  18.     {
  19.         //Count whenever new line is encountered
  20.         if (chr == 'n')
  21.         {
  22.             count_lines = count_lines + 1;
  23.         }
  24.         //take next character from file.
  25.         chr = getc(fileptr);
  26.     }
  27.     fclose(fileptr); //close file.
  28.     printf("There are %d lines in %s  in a file\n", count_lines, filechar);
  29.     return 0;
  30. }

$ cc pgm49.c
$ a.out
Enter file name: pgm2.c
There are 43 lines in pgm2.c  in a file

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at other example programs on File Handling, go to File Handling. If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.