Below is a complete C program that searches for a specified word within a text file and reports whether it is found.
#include <stdio.h>
#include <string.h>int main() {
FILE *file;
char filename[100];
char searchWord[100];
char buffer[1024];
int found = 0;
int lineNumber = 0;// Get file name and word from user
printf("Enter the file name: ");
scanf("%s", filename);
printf("Enter the word to search: ");
scanf("%s", searchWord);// Open the file in read mode
file = fopen(filename, "r");
if (file == NULL) {
printf("Error: Could not open file %s ", filename);
return 1;
}// Read the file line by line
while (fgets(buffer, sizeof(buffer), file) != NULL) {
lineNumber++;
// strstr checks if searchWord exists in the current line
if (strstr(buffer, searchWord) != NULL) {
printf("Word %s found on line %d ", searchWord, lineNumber);
found = 1;
}
}// Close the file
fclose(file);if (!found) {
printf("Word %s not found in the file. ", searchWord);
}return 0;
}
How It Works?
1.Get Input: The program prompts the user for a file name and the word to search for.
2.Open File: fopen(filename, "r") opens the file in read mode. If the file does not exist, it prints an error and exits .
3.Read Line by Line: fgets(buffer, sizeof(buffer), file) reads one line at a time into the buffer. This continues until the end of the file is reached.
4.Search with strstr: The strstr(buffer, searchWord) function checks if the search word appears anywhere within the current line. It returns a pointer to the first occurrence, or NULL if not found.
5.Report Results: If found, it prints the line number. A flag found tracks whether the word was seen at least once; if not, a "not found" message is printed at the end.
Example
Suppose you have a file named sample.txt with the following content:
Hello world
This is a C programming tutorial
Search for the word world
Run:
Enter the file name: sample.txt
Enter the word to search: world
Output:
Word world found on line 1
Word world found on line 3