C Program to count the words in a file.
Objective
Write a C program to count the total number of words in a text file.
Algorithm / Approach
- Open the file in Read mode.
- Read characters in a loop using
fgetc()untilEOF. - If the character is a space (
' '), increment a word counterc. - If the character is a newline (
'\n'), add the current line's words to thetotal(total = total + c + 1) and resetc = 0. - Print the total word count.
main.c
#include<stdio.h>
int main( ) {
FILE *fptr;
char ch;
int c=0, total=0;
fptr = fopen("prowess.txt","r");
if(fptr != NULL) {
ch = fgetc(fptr);
while(ch!=EOF){
if(ch==' '){
c++;
}
else if(ch=='\n'){
total=total+c+1;
c=0;
}
ch = fgetc(fptr);
}
printf("TOTAl WORDS: %d",total);
return 0;
}
Expected Output
FILE CONTENT IS: C is a simple language. TOTAL WORDS: 5
Explanation of the Program
- Counting words mathematically equates to counting the spaces between them. A line with 4 spaces contains 5 words.
- Because text files can have multiple lines, we must also track newline characters. Every time a line ends, we take the space count, add 1 (for the final word on that line), add it to our grand total, and reset the space counter for the next line.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)