Replace a Word in a Text File — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Replace a Word with Another Word in a Text File

In this tutorial, you'll learn how to replace a word with another word in a text file using the C programming language. This is essentially a from-scratch implementation of sed 's/old/new/g' — you read the original file line by line, replace every occurrence of the target word in each line, write the updated line to a temporary file, and then swap the temporary file in for the original. The strstr() function does the heavy lifting for the actual replacement.

C program to replace a word with another word in a text file using a temporary file, strstr, and fputs, with step-by-step explanation.

📝 Problem Statement

Write a program in C to replace a word with another word in a text file.

⚙️ How the Program Works

The program uses the same "copy-and-replace" pattern as Problem 6 (delete a line), but with a twist — inside each line, occurrences of the old word are replaced by the new word:

  1. Ask for the filename, the old word, and the new word.
  2. Open the original file in read mode ("r") and a temporary file in write mode ("w").
  3. Read the original line by line with fgets().
  4. For each line, replace every occurrence of the old word: use a loop with strstr() to find each match, copy the text before the match, then copy the new word, and advance past the old word. Repeat until no more matches are found. Then copy the rest of the line.
  5. Write the modified line to the temporary file with fputs().
  6. Close both files, then remove() the original and rename() the temporary file to the original name.

💻 Complete C Program

#include <stdio.h> #include <string.h> #include <stdlib.h> #define BUFSIZE 4096 static void replace_all(const char *line, const char *old_word, const char *new_word, char *out, size_t out_size) { const char *pos = line; const char *match; size_t old_len = strlen(old_word); size_t new_len = strlen(new_word); size_t used = 0; while ((match = strstr(pos, old_word)) != NULL) { /* Copy the part before the match */ size_t before = (size_t)(match - pos); if (used + before + new_len + 1 >= out_size) break; memcpy(out + used, pos, before); used += before; /* Write the replacement */ memcpy(out + used, new_word, new_len); used += new_len; /* Advance past the old word */ pos = match + old_len; } /* Copy the rest of the line (including the trailing \n) */ size_t rest = strlen(pos); if (used + rest >= out_size) rest = out_size - used - 1; memcpy(out + used, pos, rest); used += rest; out[used] = '\0'; } int main(void) { FILE *src, *tmp; char filename[100]; char old_word[100], new_word[100]; char line[BUFSIZE], out[BUFSIZE]; int replaced = 0; printf("Enter the filename: "); scanf("%99s", filename); printf("Enter the word to replace: "); scanf("%99s", old_word); printf("Enter the replacement word: "); scanf("%99s", new_word); if (strlen(old_word) == 0) { printf("Error: The word to replace cannot be empty.\n"); return 1; } src = fopen(filename, "r"); if (src == NULL) { printf("Error: Could not open '%s'.\n", filename); return 1; } tmp = fopen("temp.txt", "w"); if (tmp == NULL) { printf("Error: Could not create temporary file.\n"); fclose(src); return 1; } while (fgets(line, BUFSIZE, src) != NULL) { replace_all(line, old_word, new_word, out, BUFSIZE); if (strcmp(line, out) != 0) replaced = 1; fputs(out, tmp); } fclose(src); fclose(tmp); if (!replaced) { printf("Word '%s' not found. File unchanged.\n", old_word); remove("temp.txt"); return 0; } if (remove(filename) != 0) { printf("Error: Could not remove the original file.\n"); return 1; } if (rename("temp.txt", filename) != 0) { printf("Error: Could not rename temporary file to '%s'.\n", filename); return 1; } printf("Replaced all occurrences of '%s' with '%s' in '%s'.\n", old_word, new_word, filename); return 0; }

🖥️ Sample Output

Assume sample.txt contains:

Contents of sample.txt before: The quick brown fox jumps over the lazy dog.
The dog barked. The fox ran.
The dog and the fox are friends.

Running the program to replace dog with cat:

Console: Enter the filename: sample.txt
Enter the word to replace: dog
Enter the replacement word: cat
Replaced all occurrences of 'dog' with 'cat' in 'sample.txt'.

After the program finishes, sample.txt contains:

Contents of sample.txt after: The quick brown fox jumps over the lazy cat.
The cat barked. The fox ran.
The cat and the fox are friends.

🔍 Line-by-Line Explanation

Line / Code Explanation
#define BUFSIZE 4096 Large enough for most lines. If a line is longer, fgets splits it into multiple chunks — the replacement still works, just per chunk.
replace_all(...) A helper function that builds the modified line in out. Splitting this out makes main easier to read.
strstr(pos, old_word) Finds the next occurrence of old_word starting at pos. Returns NULL when no match remains.
match - pos The number of characters between pos and the match — i.e., the prefix to copy verbatim.
memcpy(out + used, pos, before) Copies the prefix into the output buffer.
memcpy(out + used, new_word, new_len) Writes the replacement word.
pos = match + old_len; Advances past the old word so the next search starts after it.
memcpy(out + used, pos, rest) Copies everything after the last match — including the trailing newline.
if (strcmp(line, out) != 0) replaced = 1; Detects whether any line changed. If nothing changed, the original file is left untouched.
remove(filename); rename("temp.txt", filename); Atomically swaps the temporary file in for the original.
⚠️ Important: This program performs a literal substring replacement, which means "dog" will also be replaced inside "dogged" and "hotdog". If you want whole-word replacement only, you need to inspect the characters before and after each match — see the "Whole-Word Replacement" section below.

🧠 How the Replacement Loop Works

The trick is to think of the line as three pieces at each step: prefix (text before the match), match (the word being replaced), and suffix (everything after). The loop:

  • Copies the prefix into the output buffer.
  • Copies the replacement word into the output buffer.
  • Advances pos past the match, so the next iteration treats the suffix as the new input.
  • Repeats until strstr returns NULL.
  • Finally copies whatever remains of the line (including the trailing newline).

This is O(n) per line — every character is visited at most twice — and it handles multiple matches per line and overlapping regions correctly without any special cases.

🎯 Whole-Word Replacement

To replace only whole words — so "dog" matches "dog" but not "dogged" — check that the character immediately before and after the match is not alphanumeric. Insert these checks into the replacement loop:

  • Let before_char = (match == pos) ? ' ' : match[-1] — the character just before the match, or a space if the match is at the start of the buffer.
  • Let after_char = match[old_len] — the character just after the match.
  • If isalnum(before_char) || isalnum(after_char), the match is part of a larger word — skip it by advancing pos = match + 1 instead of replacing.
  • Otherwise, perform the replacement as usual.

Include <ctype.h> for isalnum.

🐛 Common Pitfalls

  • Empty old word: strstr(line, "") always returns the start of the string, so replacing an empty word would infinite-loop. This program explicitly rejects an empty old_word.
  • Forgetting to close before remove: On Windows, remove and rename fail if either file is still open. Close both handles first.
  • Buffer overflow from longer replacement: If the new word is longer than the old one, the output line can grow. The out_size guard in replace_all truncates the line if it exceeds BUFSIZE, preventing overflow — but you may want to enlarge the buffer for very long replacements.
  • Forgetting the trailing newline: The final memcpy copies the rest of the line, including \n. If you accidentally strip it, the destination file will end up with all lines glued together.
  • Case sensitivity: strstr is case-sensitive. To match case-insensitively, lowercase both the line and the old word before comparing.
  • Missing NULL checks: Both fopen calls must be checked before proceeding.

💡 Tips & Best Practices

  • Print a summary after replacement: how many lines were modified, how many replacements were made.
  • Back up the original file (rename it to filename.bak) before replacing, so the user can revert if needed.
  • For a more robust temp file, use tmpfile() or generate a unique name with tmpnam() instead of hard-coding "temp.txt".
  • Compile with gcc -Wall -Wextra -std=c11 -g to catch unused variables and format-string issues.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 2. Search for a Specific Word in a Text File
  • 6. Delete a Specific Line from a Text File
  • 12. Sort the Lines of a Text File in Alphabetical Order
  • 15. Copy the Contents of One Text File into Another
  • File Handling in C — Introduction
  • Files FAQ

Previous Problem: -->> 9. Merge Multiple Text Files into a Single Text File   ||   Next Problem: -->> 11. Encrypt the Contents of a Text File

Back to Index: -->> File Handling Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.