Introduction
In this post, I am going to write a c program to find a word in a file. This program will display all its positions in a file. Before writing this program, let’s see the input file and the expected output.
Also Read: Switch Case in C Program to Calculate Area of Circle and Triangle
Input file : abc.txt
We will open this file in reading mode. The contents of this file are
My name is Vijay londhe.
Vijay means success.
You can me Vijay or Viju.
This is just a sample file. In this file, we are going to search word “Vijay”. For better understanding let’s see the following expected output.
Expected Output
Enter a word to search
Vijay
Vijay is found at the position 4 from the beginning
Vijay is found at the position 6 from the beginning
Vijay is found at the position 12 from the beginning
As you can see the above output, we are getting all positions for the word “Vijay”. Kindly note that this program is case sensitive.
Also Read: C Language Program to Count the Number of Lowercase Letters in a Text File
Now, it is time to see the c program for this.
C Program to Find a Word in a File
In this program, I am using the file handling function fgetc() for reading a file.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char word[15],str[200];
char ch;
int i=0,j=0,pos=0,cmp,flag=0;
printf("Enter a word to search\n");
scanf("%s",word);
fp=fopen("abc.txt","r");
while((ch=fgetc(fp))!=EOF)
{
if((ch==' ')||(ch=='\n'))
{
pos++;
cmp=strcmp(str,word);
if(cmp==0)
{
printf("%s is found at the position %d from the beginning\n",word,pos);
flag=1;
}
for(i=j;i>=0;i--)
{
str[i]='\0';
}
j=0;
continue;
}
str[j]=ch;
j++;
}
pos++;
cmp=strcmp(str,word);
if(cmp==0)
{
printf("%s is found at %d position from the beginning\n",word,pos);
}
else if(flag==0)
{
printf("%s is not found in this file",word);
}
return 0;
}
The above c program is finding a word in a file and displaying all its positions. Now, see the detailed explanation.
Also Read: Program in C to Replace Capital C with Capital S in a File
Explanation
FILE *fp;
Here, we are creating a file pointer of type FILE.
char word[15],str[200];
We have declared two character arrays i.e. strings here. The variable word will store the string that we need to search in a file. The str is storing every word from the file. Because, we will compare these two variables.
char ch;
In this program, we are reading a file character by character. So, we will use the variable ch for storing the read character from the file.
int i=0, j=0, pos=0, cmp, flag=0;
These are some integer variables. The variable i and j are loop variables. The pos=0 is for displaying the positions of a word in a file. We will compare two strings using strcmp() function and that result will be stored in this variable cmp. There is the possibility that we can not get a single position of the word, then using this variable flag we can decide whether a word is present in a file or not.
Also Read: C Program to Remove White Spaces and Comments from a File
printf(“Enter a word to search\n”);
We are simply displaying a message for user to enter a word to search in a file.
scanf(“%s”,word);
This statement read the string from the console and will store in a variable “word”.
fp=fopen(“abc.txt”,”r”);
Here, we are opening a file abc.txt in reading mode.
while((ch=fgetc(fp))!=EOF)
Here, we are reading a single character from the file using fgetc() function and storing that character in the variable ch. We are doing this in the while loop. So, we are doing this until we reach the EOF i.e. end of the file.
Also Read: C Program to Find the Sum of Cubes of Elements in an Array
if(( ch == ‘ ‘ ) || ( ch == ‘\n’ ))
The words are always separated by blank space. In this statement, we are verifying whether we got blank space or new line. If any condition is true, then whole condition will become true. Why we are using this statement. This statement will tell us that we got the word. Because, we are reading a character and storing in the variable str. If we get space that means we got a word. Now, here we will is this word is matching with our word.
pos++;
The variable pos will tell us the position of the our word. Therefore, whenever we will reach in the above statement, we will increment the value of pos.
cmp = strcmp ( str, word ) ;
Here, we have used the string manipulation function i.e. strcmp() to compare two strings. If these two strings are equal then this function will return 0 and it will be stored in the variable cmp.
Also Read: Floyd Triangle in C Programming
We got our word in a file.
See the following code.
if(cmp==0)
{
printf("%s is found at the position %d from the beginning\n",word,pos);
flag=1;
}
As I said earlier, when both the strings are equal, then the value of cmp will become zero. So here, we are checking if the value of cmp is zero, then we will display the current position of this word using the variable pos.
Go to the next word
In this section, we are deleting the existing word which is stored in the variable str. Because we are going to store the next word in this variable. See the following code.
for(i=j;i>=0;i--)
{
str[i]='\0';
}
j=0;
continue;
For deleting the existing word from the variable str, we have used for loop. Using the variable j, we were storing each and every character in the string str. We are decrementing the value of i and storing the null character in the variable str. After that we are making the value of j is equal to zero.
Now, we are skipping the further steps and using the continue statement, we will directly go to the beginning of the while loop.
Also Read: Arrays in C for Complete Beginners
str[j]=ch;
This statement is written outside the if statement. Here, we are storing the value of ch to the string str at the location of j.
j++;
This is incrementing the value of j by 1.
End of the while loop
In the above while loop, we are reading the character from the file, storing that character in the string str. If we get the blank space or new line, then we will go for the match of the two words. If we get a match, then we will display its position and will change the value of flag=1.
But, there is a one problem. We are not able to compare last word of the file. Because there is EOF and we come out of the loop. So we are writing the following statements to compare the last word of the file and our word. See the following code.
pos++;
cmp=strcmp(str,word);
if(cmp==0)
{
printf("%s is found at %d position from the beginning\n",word,pos);
}
else if(flag==0)
{
printf("%s is not found in this file",word);
}
In the above code, we are also checking whether we got our match or not. And we are doing this using the variable flag. If the value of flag remains zero, then we will display that the given word is not found in the file.
Also Read: C Program to Copy the Contents of One File into Another File
So, here I have written a c program to find a word in a file using fgetc() function. We can write the same c program to find a word in a file using fgets() function.
I hope you liked this article. If you still have any doubts or some feedback, please contact me.
Thank you.