In this tutorial, you'll learn how to search for a specific word in a text file and count how many times it occurs using the C programming language. This is one of the most practical file-handling exercises — it's used in log analysis, word-frequency counters, and simple grep-like utilities. The program reads the file line by line with fgets(), then scans each line using strstr() to find every occurrence of the target word.
📝 Problem Statement
Write a program in C to search for a specific word in a text file and display its occurrences.
⚙️ How the Program Works
The program follows a simple read-and-scan pattern:
- Ask the user for the word to search and the filename (or hard-code the filename).
- Open the file in read mode with
fopen("filename.txt", "r")and check forNULL. - Read line by line using
fgets()into a buffer untilEOF. - Search each line with
strstr(). Each time it returns a non-NULLpointer, increment the count and advance past the match. - Close the file with
fclose()and print the total.
💻 Complete C Program
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE *fp;
char filename[100];
char word[50];
char line[1024];
int count = 0;
printf("Enter the filename: ");
scanf("%99s", filename);
printf("Enter the word to search: ");
scanf("%49s", word);
fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Error: Could not open file '%s'.\n", filename);
return 1;
}
while (fgets(line, sizeof(line), fp) != NULL)
{
char *ptr = line;
while ((ptr = strstr(ptr, word)) != NULL)
{
count++;
ptr += strlen(word);
}
}
fclose(fp);
printf("The word '%s' appears %d time(s) in '%s'.\n",
word, count, filename);
return 0;
}🖥️ Sample Output
Assume sample.txt contains the following lines:
sample.txt:
The quick brown fox jumps over the lazy dog.The dog barked. The fox ran.
The dog and the fox are friends.
Running the program:
Enter the word to search: dog
The word 'dog' appears 3 time(s) in 'sample.txt'.
🔍 Line-by-Line Explanation
| Line / Code | Explanation |
|---|---|
#include <string.h> |
Provides strstr() and strlen(). |
scanf("%99s", filename) |
Reads a filename without spaces. The %99s limit prevents buffer overflow. |
fopen(filename, "r") |
Opens the file in read mode. Returns NULL on failure. |
fgets(line, sizeof(line), fp) |
Reads one line (up to 1023 characters) into the buffer. Returns NULL at end of file. |
strstr(ptr, word) |
Returns a pointer to the first occurrence of word inside ptr, or NULL if not found. |
ptr += strlen(word) |
Moves past the current match so the next iteration finds overlapping occurrences correctly. |
fclose(fp) |
Releases the file handle. Always call this. |
🔁 Case-Insensitive Variation
For most real-world searches you'll want a case-insensitive match. The trick is to convert each line and the target word to lowercase before calling strstr(). Here is a compact version using tolower() from <ctype.h>:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void to_lower(char *s)
{
for (; *s; s++)
*s = (char)tolower((unsigned char)*s);
}
int main(void)
{
FILE *fp;
char filename[100], word[50], line[1024];
int count = 0;
printf("Enter the filename: ");
scanf("%99s", filename);
printf("Enter the word to search: ");
scanf("%49s", word);
to_lower(word);
fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Error: Could not open file.\n");
return 1;
}
while (fgets(line, sizeof(line), fp) != NULL)
{
char *ptr;
to_lower(line);
ptr = line;
while ((ptr = strstr(ptr, word)) != NULL)
{
count++;
ptr += strlen(word);
}
}
fclose(fp);
printf("The word appears %d time(s).\n", count);
return 0;
}🎯 Whole-Word Matching
The program above will also count "dog" inside "dogged" or "hotdog", because strstr matches substrings. If you need to count only whole words — where the match must be surrounded by non-alphabetic characters — you need to inspect the characters before and after each match:
- Let
ptrpoint to a match found bystrstr. - Check
ptr[-1](orline[0]ifptr == line): it must not be a letter or digit. - Check
ptr[len]: it must not be a letter or digit. - If both checks pass, count the match; otherwise skip it.
This is a good stretch exercise — it combines strstr with manual pointer inspection and isalpha() / isdigit().
💡 Tips & Best Practices
- Always limit
scanfwidths —%99s,%49s— to prevent buffer overflows. - Use a generous line buffer (1024 bytes here). If a line is longer than the buffer,
fgetswill return it in chunks; the search will still work but a single logical line may be split. - Check
fopenforNULLbefore using the pointer. - Compile with
gcc -Wall -Wextra -std=c11 -gto catch common mistakes.