C program to find and replace a word in a File by another given word - GeeksforGeeks

09 Sep, 2021
Pre-requisite: File Handling in CGiven 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’. 
Examples: 
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+ modeCheck for the file to be opened correctlyRead the contents of the existing input file word by wordAs 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 printfNow again we shift the filepointer at the beginning of the file and print the file contents of the output 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: 
C
// C program to find and replace a word// in a File by another given word #include <stdio.h>#include <stdlib.h>#include <string.h> // Function to find and// replace a word in Filevoid findAndReplaceInFile(){    FILE *ifp, *ofp;    char word[100], ch, read[100], replace[100];    int word_len, i, p = 0;     ifp = fopen("file_search_input.txt", "r");    ofp = fopen("file_replace_output.txt", "w+");    if (ifp == NULL || ofp == NULL) {        printf("Can't open file.");        exit(0);    }    puts("THE CONTENTS OF THE FILE ARE SHOWN BELOW :\n");     // displaying file contents    while (1) {        ch = fgetc(ifp);        if (ch == EOF) {            break;        }        printf("%c", ch);    }     puts("\n\nEnter the word to find:");    fgets(word, 100, stdin);     // removes the newline character from the string    word[strlen(word) - 1] = word[strlen(word)];     puts("Enter the word to replace it with :");    fgets(replace, 100, stdin);     // removes the newline character from the string    replace[strlen(replace) - 1] = replace[strlen(replace)];     fprintf(ofp, "%s - %s\n", word, replace);     // comparing word with file    rewind(ifp);    while (!feof(ifp)) {         fscanf(ifp, "%s", read);         if (strcmp(read, word) == 0) {             // for deleting the word            strcpy(read, replace);        }         // In last loop it runs twice        fprintf(ofp, "%s ", read);    }     // Printing the content of the Output file    rewind(ofp);    while (1) {        ch = fgetc(ofp);        if (ch == EOF) {            break;        }        printf("%c", ch);    }     fclose(ifp);    fclose(ofp);} // Driver codevoid main(){    findAndReplaceInFile();}
How to execute the above code:
Copy the source code from here and paste it in an offline IDESave 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
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
Output:
simmytarika5
C-File Handling
C Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
How to Append a Character to a String in C
C program to sort an array in ascending order
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string