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

CServer Side ProgrammingProgramming

A file is a physical storage location on disk and a directory is a logical path which is used to organise the files. A file exists within a directory.

The three operations that we can perform on file are as follows −

  • Open a file.
  • Process file (read, write, modify).
  • Save and close file.


Consider an example given below −

  • Open a file in write mode.
  • Enter statements in the file.

The input file is as follows −

Hi welcome to my world
This is C programming tutorial
From tutorials Point

The output is as follows −

Number of characters = 72

Total words = 13

Total lines = 3


Following is the C program to count characters, lines and number of words in a file

 Live Demo

#include <stdio.h>
#include <stdlib.h>
int main(){
   FILE * file;
   char path[100];
   char ch;
   int characters, words, lines;
   printf("enter the text.press cntrl Z:\n");
   while((ch = getchar())!=EOF){
   printf("Enter source file path: ");
   scanf("%s", path);
   file = fopen(path, "r");
   if (file == NULL){
      printf("\nUnable to open file.\n");
   characters = words = lines = 0;
   while ((ch = fgetc(file)) != EOF){
   if (ch == '\n' || ch == '\0')
   if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
   if (characters > 0){
   printf("Total characters = %d\n", characters);
   printf("Total words = %d\n", words);
   printf("Total lines = %d\n", lines);
   return 0;


When the above program is executed, it produces the following result −

enter the text.press cntrl Z:
Hi welcome to Tutorials Point
C programming Articles
Best tutorial In the world
Try to have look on it
All The Best
Enter source file path: counting.txt

Total characters = 116
Total words = 23
Total lines = 6
Published on 31-Aug-2021 12:54:24