Quick links
Write a C program to find occurrence of a word in file. How to find first or last occurrence of a word in file in C programming. Logic to find occurrence of a word in file in C program. How to search first and last occurrence of a word in file in C programming.
Required knowledge
Basic Input Output, String, Functions, Pointers, File Handling
Logic to find occurrence of a word in file
Step by step descriptive logic to find first occurrence of a word in file.
- Input source file in which you need to search, store its reference to
fptr
. - Input word to search in file, store it in some variable say
word
. - Initialize two variables
line = -1
andcol = -1
. They will store index of line and column of searched word in file. - Read a line from file, store it in
str
. - Increment
line
count by one. - Find first index of
word
instr
and store it incol
. Ifword
is found instr
then printline
andcol
which is required index and jump to step 8.Now, here’s the tricky part. I have used
strstr()
C library function. It returns pointer to first occurrence of a given word in a string. To find first occurrence ofword
instr
usepos = strstr(str, word);
(wherepos
is pointer to character).pos
will point to first occurrence ofword
instr
if exists, otherwise points toNULL
. Checkif(pos != NULL)
then find column index usingcol = pos - str
. - Repeat step 4-6 till end of file.
- Close
fptr
file to release all resources.
Program to find occurrence of a word in file
Wondering how (pos - str)
gives index of occurrence of word
. Then, please give a moment to read pointer arithmetic in C programming.
Suppose <strong>data/file3.txt</strong>
contains.
Output
Enter file path: data/file3.txt Enter word to search in file: Codeforwin 'Codeforwin' found at line: 2, col: 32
Logic to find last occurrence of a word is almost similar. I am leaving logic to you, so that you can practice a bit. However, I have written program to find last index of a word in file.
Program to find last occurrence of a word in file
Output
Enter file path: data/file3.txt Enter word to search in file: Codeforwin Last index of 'Codeforwin' line: 4, col: 27
Happy coding