C program to find and replace a word in a File by another given word
Pre-requisite: File Handling in C
Given a file containing some text, and two strings wordToBeFind and wordToBeReplacedWith, the task is to find all occurrences of the given word ‘wordToBeFind’ in the file and replace them with the given word ‘wordToBeReplacedWith’.
Input : File = "xxforxx xx for xx", wordToBeFind = "xx", wordToBeReplacedWith = "geeks" Output : geeksforgeeks geeks for geeks
Approach: The idea here is to read the contents from the given file, process the find and replace, and then store the output in another file.
- Make objects of FILE (ifp and ofp)
- Open two files, one for file input in read mode and another in write+ mode
- Check for the file to be opened correctly
- Read the contents of the existing input file word by word
- As using fgets takes the input of new line character(i.e. enter key) also we just copy the null character of the string one position back so that the newline is replaced with “\0”
- We run a loop till the end of file is reached and scan each word in the file and store it in a variable “read”.
- Then we compare “read” with “wordToBeFind” and if the result is true, we use “strcpy()” to replace “read” with “wordToBeReplacedWith”.
- Show the word replacement through printf
- Now again we shift the filepointer at the beginning of the file and print the file contents of the output file.
Below is the implementation of the above approach:
How to execute the above code:
- Copy the source code from here and paste it in an offline IDE
- Save the program.
- Create a file named “file_search_input.txt” and save it in the folder where you saved the above-copied program.
- Now open the terminal or offline IDE and run the program