C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Find frequency of a word in file

C Program: Find frequency of a word in file

C

#include <stdio.h>

#include <string.h>

 

int main() {

    FILE *file;

    char filename[100], word[50], temp[50];

    int count = 0;

 

    // Step 1: Get file name and word from user

    printf("Enter file name: ");

    scanf("%s", filename);

 

    printf("Enter the word to find: ");

    scanf("%s", word);

 

    // Step 2: Open the file in read mode

    file = fopen(filename, "r");

 

    // Step 3: Check if file exists

    if (file == NULL) {

        printf("Error! Cannot open file.\n");

        return 1;

    }

 

    // Step 4: Read words one by one from the file

    while (fscanf(file, "%s", temp) != EOF) {

        // Step 5: Compare the read word with the input word

        if (strcmp(temp, word) == 0) {

            count++;

        }

    }

 

    // Step 6: Display result

    printf("\nThe word '%s' occurs %d time(s) in the file.\n", word, count);

 

    // Step 7: Close file

    fclose(file);

 

    return 0;

}

Output

 
File (data.txt):
C programming is fun.
C is powerful.
Learning C is easy.

Input: 
Enter file name: data.txt
Enter the word to find: C

OUTPUT :
The word 'C' occurs 3 time(s) in the file.

Explanation

Step

Description

1

Prompts user for filename and target word.

2

Opens file in read mode ("r").

3

Checks whether the file exists.

4

Reads each word using fscanf() until end of file.

5

Compares each word with the user-given word using strcmp().

6

Counts and prints the number of occurrences.

7

Closes the file.