C program to count occurrences of a word in file

Quick links

Write a C program to count occurrences of a word in file. How to count occurrences of a word in file in C programming. Logic to count all occurrence of a word in file in C program.

Required knowledge

Basic Input Output, String, Functions, Pointers, File Handling

In previous post I explained to search occurrences of a word in a file. In this post we will move a step further and will learn to count all occurrences of a word in file.

Logic to count occurrences of a word in file

Step by step descriptive logic to count occurrences of a word in file.

  1. Open source file in r (read) mode, store its reference to fptr.
  2. Input word to search from user, store it in word.
  3. Initialize a variable count = 0 to store total occurrences of word.
  4. Read a line from file and store it in str.
  5. Increment count by one, if an occurrence of word is found in str.

    For this post I am not going to explain in detail how to find occurrence of a word in file. Please go through my previous post to find occurrences of a word in file.

  6. Repeat step 4-5 till end of file.
  7. Finally close fptr to release all resources.

To make things simple and more maintainable, I have used functions. I have written entire logic to count occurrences of word inside a countOccurrences() function.

Program to count occurrences of a word in file

/**
 * C program to count occurrences of a word in file.
 */

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

#define BUFFER_SIZE 1000

/* Function declarations */
int countOccurrences(FILE *fptr, const char *word);


int main()
{
    FILE *fptr;
    char path[100];

    char word[50];

    int wCount;

    /* Input file path */
    printf("Enter file path: ");
    scanf("%s", path);

    /* Input word to search in file */
    printf("Enter word to search in file: ");
    scanf("%s", word);

    /* Try to open file */
    fptr = fopen(path, "r");

    /* Exit if file not opened successfully */
    if (fptr == NULL)
    {
        printf("Unable to open file.\n");
        printf("Please check you have read/write previleges.\n");

        exit(EXIT_FAILURE);
    }

    // Call function to count all occurrence of word
    wCount = countOccurrences(fptr, word);

    printf("'%s' is found %d times in file.", word, wCount);


    // Close file
    fclose(fptr);

    return 0;
}


/**
 * Returns total occurrences of a word in given file.
 */
int countOccurrences(FILE *fptr, const char *word)
{
    char str[BUFFER_SIZE];
    char *pos;

    int index, count;
    
    count = 0;

    // Read line from file till end of file.
    while ((fgets(str, BUFFER_SIZE, fptr)) != NULL)
    {
        index = 0;

        // Find next occurrence of word in str
        while ((pos = strstr(str + index, word)) != NULL)
        {
            // Index of word in str is
            // Memory address of pos - memory
            // address of str.
            index = (pos - str) + 1;

            count++;
        }
    }

    return count;
}

Read more about pointer arithmetic in C programming to know how (pos - str) evaluates to index of word in str.

Suppose <strong>data/file3.txt</strong> contains.

I love programming.
I am learning C programming at Codeforwin.
Programming with files is fun.
Learning C programming at Codeforwin is simple and easy.

Output

Enter file path: data/file3.txt
Enter word to search in file: Codeforwin
'Codeforwin' is found 2 times in file.

Happy coding 😉