Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to count the words in a file.

C Code Example — File Handling Programs

ADVERTISEMENT

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

  1. Open the file in Read mode.
  2. Read characters in a loop using fgetc() until EOF.
  3. If the character is a space (' '), increment a word counter c.
  4. If the character is a newline ('\n'), add the current line's words to the total (total = total + c + 1) and reset c = 0.
  5. 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)
ADVERTISEMENT