C program to count lines, words and characters in a file

This is a C program that counts the number of lines, words and characters in a text file. At first the program prompts the user to enter the name of the file to be checked. The filename is passed as a parameter to the C Library function, fopen(). The second parameter "r" of the fopen function specifies the file should be opened in read only mode. The fopen function returns a pointer to the FILE object if the file is opened successfully.

The file is then read one character at a time using the fgetc() library function inside a while loop until the End of File (EOF) is reached. Character count is incremented with each iteration of the loop, word count is incremented when a Space character is encountered and line count is incremented for each new line character that is read.

Finally, linecount and wordcount are incremented by one if the character count is more than zero. Without this step the final word and line won't be counted.

Program Source Code

 * C program to count no of lines, words and 	 *
 * characters in a file.			 *

#include <stdio.h>

int main()
 FILE *fp;
 char filename[100];
 char ch;
 int linecount, wordcount, charcount;

 // Initialize counter variables
 linecount = 0;
 wordcount = 0;
 charcount = 0;

 // Prompt user to enter filename
  printf("Enter a filename :");
    // Open file in read-only mode
   fp = fopen(filename,"r");

   // If file opened successfully, then write the string to file
   if ( fp )
	//Repeat until End Of File character is reached.	
	   while ((ch=getc(fp)) != EOF) {
	   	  // Increment character count if NOT new line or space
		    if (ch != ' ' && ch != '\n') { ++charcount; }
		  // Increment word count if new line or space character
		   if (ch == ' ' || ch == '\n') { ++wordcount; }
		  // Increment line count if new line character
		   if (ch == '\n') { ++linecount; }


	   if (charcount > 0) {
         printf("Failed to open the file\n");

    printf("Lines : %d \n", linecount);
    printf("Words : %d \n", wordcount);
    printf("Characters : %d \n", charcount);


Sample Output

Consider a text file named wolf.txt with the following content:

Help Help, 
Go away you naughty wolf.

With the above file as input, the program will be show the result as below

Enter a filename :wolf.txt
Lines : 2
Words : 7
Characters : 30

Post a comment


Your Comment

Email (We dont publish it)


Manya | April 25, 2016 9:34 PM |

very much impressed

Manya | April 25, 2016 9:34 PM |

i am very much impressed where were you guys all along. now i can implement this in my little project

Manya | April 25, 2016 9:34 PM |

i am very much impressed keep it up guys

philips05 | July 25, 2016 10:59 PM |

Excellent approach to share these source lines on programming. I really impressed from this work.

adarsh | September 10, 2016 6:22 PM |

How to the to find the no of files ?