C Program to Count Words in a File

We discussed different ways to count words in a string in this article. Here we’ll extend that to count all words in a file. We can think of a file as a collection of lines. We’ll count words of each line one by one and add them up.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_LEN 1024

int count_word(char *str) {
  int count = 0;
  char* token = strtok(str, " ");
  while (token != NULL) {
    count++;
    token = strtok(NULL, " ");
  }

  return count;
}

int main() {
  FILE *fp;
  char *line = NULL;
  size_t len = 0;
  int count = 0;
  
  fp = fopen("sample.txt", "r");
  if (fp == NULL) return -1;

  while (getline(&line, &len, fp) != -1) {
    count += count_word(line);
  }
  
  if (line) free(line);
  
  fclose(fp);

  printf("Number of words in the file is %d.\n", count);
  return 0;
}

This program first opens the file, sample.txt, in read-only mode. The next while loop reads one line at a time using the getline() function. The read line is passed to the count_word() function that returns the number of words in the line. The returned number is added to the count variable.

The loop will terminate when there will be no line to read in the file. The count variable accumulates the word counts of each line. So, at the end of the loop it will hold the word count of the file.

The count_word() function uses strtok() function to split a line. The next loop counts the words of the line.

Here is the content of the input file.

$ cat sample.txt
All sorts of things and weathers
Must be taken in together
To make up a year
And a sphere

It has 19 words in 4 lines.

Here is the output of the above program.

$ cc test.c -o test
[polaris@localhost del]$ ./test
Number of words in the file is 19.

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

1
0
0
0
2
0