Search a Word in a Text File — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Search for a Specific Word in a Text File and Display Its Occurrences

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.

C program to search for a specific word in a text file and count its occurrences using fgets and strstr, with step-by-step explanation.

📝 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:

  1. Ask the user for the word to search and the filename (or hard-code the filename).
  2. Open the file in read mode with fopen("filename.txt", "r") and check for NULL.
  3. Read line by line using fgets() into a buffer until EOF.
  4. Search each line with strstr(). Each time it returns a non-NULL pointer, increment the count and advance past the match.
  5. 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:

Contents of 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:

Console: Enter the filename: sample.txt
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.
⚠️ Important: This program performs a case-sensitive search. "Dog" and "dog" are counted separately. To make it case-insensitive, convert both the line and the word to lowercase before comparing — see the next section.

🔁 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 ptr point to a match found by strstr.
  • Check ptr[-1] (or line[0] if ptr == 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 scanf widths — %99s, %49s — to prevent buffer overflows.
  • Use a generous line buffer (1024 bytes here). If a line is longer than the buffer, fgets will return it in chunks; the search will still work but a single logical line may be split.
  • Check fopen for NULL before using the pointer.
  • Compile with gcc -Wall -Wextra -std=c11 -g to catch common mistakes.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 1. Create a New Text File and Write Text in It
  • 4. Read and Display the Contents of a Text File
  • 5. Count Characters, Words, and Lines in a Text File
  • 10. Replace a Word with Another Word in a Text File
  • File Handling in C — Introduction
  • Files FAQ

Previous Problem: -->> 1. Create a New Text File and Write Text in It   ||   Next Problem: -->> 3. Append Data to an Existing Binary File

Back to Index: -->> File Handling Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.