Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Lex code to replace a word with another word in a file
Next article icon

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

Last Updated : 27 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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’. 

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.

  1. Make objects of FILE (ifp and ofp)
  2. Open two files, one for file input in read mode and another in write+ mode
  3. Check for the file to be opened correctly
  4. Read the contents of the existing input file word by word
  5. 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"
  6. 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".
  7. Then we compare "read" with "wordToBeFind" and if the result is true, we use "strcpy()" to replace "read" with "wordToBeReplacedWith".
  8. Show the word replacement through printf
  9. 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 File void 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 code void main() {     findAndReplaceInFile(); } 

How to execute the above code:

  1. Copy the source code from here and paste it in an offline IDE
  2. Save the program.
  3. Create a file named "file_search_input.txt" and save it in the folder where you saved the above-copied program.
  4. Now open the terminal or offline IDE and run the program

Output:

Output from codeblocks IDE

Time complexity: O(n)

Where n is the number of characters in the file being searched. This is because the time taken for this algorithm is directly proportional to the number of characters in the file.

Space complexity: O(1)

This algorithm does not use any additional data structures and hence the space complexity is constant, O(1).


Next Article
Lex code to replace a word with another word in a file

A

ab1998dob
Improve
Article Tags :
  • Strings
  • C Programs
  • DSA
  • C-File Handling
Practice Tags :
  • Strings

Similar Reads

  • C Program to Replace a Word in a Text By Another Given Word
    Given three strings 'str', 'oldW' and 'newW'. The task is find all occurrences of the word 'oldW' and replace then with word 'newW'. Examples: Input : str[] = "xxforxx xx for xx", oldW[] = "xx", newW[] = "geeks" Output : geeksforgeeks geeks for geeksRecommended: Please solve it on “PRACTICE ” first,
    3 min read
  • Lex code to replace a word with another word in a file
    Given a text file as input, the task is to replace a given word with another word in the file. Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the
    2 min read
  • Lex program to search a word in a file
    Problem: Write a Lex program to search a word in a file. Explanation: FLEX (Fast Lexical Analyzer Generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. Lex reads an input stream specifying the lexical analyzer and outputs
    2 min read
  • C Program To Reverse Words In A Given String
    Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples:  Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "
    3 min read
  • C# Program To Reverse Words In A Given String
    Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "p
    4 min read
  • C program to read a range of bytes from file and print it to console
    Given a file F, the task is to write C program to print any range of bytes from the given file and print it to a console. Functions Used: fopen(): Creation of a new file. The file is opened with attributes as “a” or “a+” or “w” or “w++”.fgetc(): Reading the characters from the file.fclose(): For clo
    2 min read
  • C program to reverse the content of the file and print it
    Given a text file in a directory, the task is to print the file content backward i.e., the last line should get printed first, 2nd last line should be printed second, and so on.Examples: Input: file1.txt has: Welcome to GeeksforGeeks Output: GeeksforGeeks to WelcomeGeeksforGeeks Input: file1.txt has
    3 min read
  • C program to append content of one text file to another
    Pre-requisite: File Handling in C Given the source and destination text files, the task is to append the content from source file to destination file and then display the content of the destination file.Examples: Input: file1.text This is line one in file1 Hello World. file2.text This is line one in
    2 min read
  • C Program to Maximize Time by Replacing ‘_’ in a Given 24-Hour Format Time
    Given a string S representing a time in 24 hours format, with '_' placed at positions of some digits, the task is to find the maximum time possible by replacing the characters '_' with any digit. Examples: Input: S = “0_:4_”Output: 09:49Explanation: Replacing the characters S[1] and S[4] with '9' mo
    2 min read
  • C Program to Read Content of a File
    In C, reading a file is a step-by-step process in which we first have to prepare the file only after which we can start reading. It involves opening the file, reading its data, and closing the file. Opening the File: Opening the file loads the file into the memory and connect the file to the program
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences