Write a C program to count number of characters, words and lines in a text file. Logic to count characters, words and lines in a file in C program. How to count total characters, words and lines in a text file in C programming.
Example
Source file
I love programming. Working with files in C programming is fun. I am learning C programming at Codeforwin.
Output
Total characters = 106 Total words = 18 Total lines = 3
Required knowledge
Basic Input Output, Pointers, String, File Handling
Logic to count characters, words and lines in a file
Step by step descriptive logic to count characters, words and lines in a text file.
- Open source file in
r
(read) mode. - Initialize three variables
characters = 0
,words = 0
andlines = 0
to store counts. - Read a character from file and store it to some variable say
ch
. - Increment
characters
count.
Incrementwords
count if current character is whitespace character i.e.if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
.
Incrementlines
count if current character is new line character i.e.if (ch == '\n' || ch == '\0')
. - Repeat step 3-4 till file has reached end.
- Finally after file has reached end increment
words
andlines
count by one if totalcharacters > 0
to make sure you count last word and line.
Also read how to find total words in a string.
Program to count characters, words and lines in a file
/**
* C program to count number of characters, words and lines in a text file.
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
char path[100];
char ch;
int characters, words, lines;
/* Input path of files to merge to third file */
printf("Enter source file path: ");
scanf("%s", path);
/* Open source files in 'r' mode */
file = fopen(path, "r");
/* Check if file opened successfully */
if (file == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
/*
* Logic to count characters, words and lines.
*/
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF)
{
characters++;
/* Check new line */
if (ch == '\n' || ch == '\0')
lines++;
/* Check words */
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}
/* Increment words and lines for last word */
if (characters > 0)
{
words++;
lines++;
}
/* Print file statistics */
printf("\n");
printf("Total characters = %d\n", characters);
printf("Total words = %d\n", words);
printf("Total lines = %d\n", lines);
/* Close files to release resources */
fclose(file);
return 0;
}
Suppose if data\file3.txt
contains
I love programming.
Working with files in C programming is fun.
I am learning C programming at Codeforwin.
Output
Enter source file path: data\file3.txt Total characters = 106 Total words = 18 Total lines = 3
Happy coding 😉