C PROGRAMMING PROGRAM • FILE HANDLING
Search for a Word in a Text File
Learn how to search for a word in a text file using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Occurrences of C = 2
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE *file = fopen("lesson.txt", "w");
if (file == NULL) return 1;
fputs("learn C and practise C every day", file);
fclose(file);
file = fopen("lesson.txt", "r");
if (file == NULL) return 1;
char word[64];
int count = 0;
while (fscanf(file, "%63s", word) == 1)
if (strcmp(word, "C") == 0) count++;
fclose(file);
printf("Occurrences of C = %d\n", count);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Occurrences of C = 2
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Read one whitespace-delimited token at a time and count exact matches.
- Display the computed result.
Read one whitespace-delimited token at a time and count exact matches.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(1)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
