Replace a Word in File in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

#include <stdio.h>
#include <string.h>

int main() {
    FILE *file = fopen("sample.txt", "r");
    FILE *temp = fopen("temp.txt", "w");
    char str[1000], word[50] = "apple", replace[50] = "orange";

    while (fgets(str, sizeof(str), file)) {
        char *pos = strstr(str, word);
        while (pos != NULL) {
            char tempStr[1000];
            int idx = pos - str;
            str[idx] = '\0';
            sprintf(tempStr, "%s%s%s", str, replace, pos + strlen(word));
            strcpy(str, tempStr);
            pos = strstr(str, word);
        }
        fputs(str, temp);
    }
    fclose(file);
    fclose(temp);
    remove("sample.txt");
    rename("temp.txt", "sample.txt");
    return 0;
}

C Output

Input:  
I like apple. Apple pie is delicious.  

Output:  
I like orange. Orange pie is delicious.


C++ Program

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ifstream fin("sample.txt");
    ofstream fout("temp.txt");
    string word = "apple", replace = "orange", line;

    while (getline(fin, line)) {
        size_t pos;
        while ((pos = line.find(word)) != string::npos)
            line.replace(pos, word.length(), replace);
        fout << line << endl;
    }
    fin.close();
    fout.close();
    remove("sample.txt");
    rename("temp.txt", "sample.txt");
    return 0;
}

C++ Output

Input:  
I like apple. Apple pie is delicious.  

Output:  
I like orange. Orange pie is delicious.


JAVA Program

import java.io.*;
public class ReplaceWord {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("sample.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("temp.txt"));
        String line;
        while ((line = br.readLine()) != null) {
            line = line.replaceAll("apple", "orange");
            bw.write(line);
            bw.newLine();
        }
        br.close();
        bw.close();
        new File("sample.txt").delete();
        new File("temp.txt").renameTo(new File("sample.txt"));
    }
}

JAVA Output

Input:  
I like apple. Apple pie is delicious.  

Output:  
I like orange. Orange pie is delicious.


Python Program

with open("sample.txt", "r") as file:
    content = file.read()

content = content.replace("apple", "orange")

with open("sample.txt", "w") as file:
    file.write(content)

Python Output

Input:  
I like apple. Apple pie is delicious.  

Output:  
I like orange. Orange pie is delicious.


In-Depth Explanation
Example
Consider that you have a text file called sample.txt containing the sentence "I like apple. Apple pie is delicious." and you need to replace all instances of the word "apple" with "orange". The objective is to alter the file content in such a way that it becomes "I like orange. Orange pie is delicious." This problem assists us in manipulating files and changing their content dynamically without editing them manually.

Real-Life Analogy
Consider this as finding and replacing something within a document in Microsoft Word. If you were instructed by your instructor to replace all occurrences of "apple" with "orange" within a 50-page paper, would you go line by line? No—You'd use "Ctrl + H" to replace all of them at once. This does the same thing programmatically, but through code—a fundamental operation when dealing with config files, logs, or auto-created content.

Why It Matters
Mastering how to replace content within a file is essential to data cleaning, log updating, batch document editing, and even text preprocessing for AI or NLP tasks. It's a fundamental yet powerful skill that educates you about reading a file, working with strings, and writing content back, solidifying the file I/O and string replacement concept—both of which are two of the most commonly requested topics in newbie interviews and coding quizzes.

What It Teaches
This exercise teaches how to:

Open and read/write files.

Do string search and replace operations.

Handle file updates safely with temporary files.

Utilize language-specific libraries (such as replace in Python or replaceAll in Java).

Understand string immutability and line-by-line operations functionality in other programming languages.

Use in Interviews or Real Projects
In coding interviews, particularly in initial rounds, you may be asked basic file operations. An interviewer can say: "Can you parse a file and replace a word?" or provide you with a configuration file and say to modify values. In actual scenarios, developers usually end up working on automation scripts that preprocess or change logs, HTML templates, markdown files, etc. This exercise is of direct application in such a role.

Replacing a term in a file with code is a simple and useful operation in both introductory programming drills and actual development situations. Whether you are developing a content-automation utility, a backend script, or even a routine data-cleaning operation, being aware of how to dynamically change file content will save time and decrease errors. Grasping this idea sets you up for file text manipulation work frequently found within Python scripting, Java automations, C/C++ legacy system modifications, or even web application development workflows. This page delivers complete functional examples and outlines the idea well so you could easily learn the replace word in file task across various languages.