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.
📝 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:
- Ask for the filename, the old word, and the new word.
- Open the original file in read mode (
"r") and a temporary file in write mode ("w"). - Read the original line by line with
fgets(). - 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. - Write the modified line to the temporary file with
fputs(). - Close both files, then
remove()the original andrename()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:
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:
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:
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. |
"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
pospast the match, so the next iteration treats the suffix as the new input. - Repeats until
strstrreturnsNULL. - 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 advancingpos = match + 1instead 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 emptyold_word. - Forgetting to close before
remove: On Windows,removeandrenamefail 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_sizeguard inreplace_alltruncates the line if it exceedsBUFSIZE, preventing overflow — but you may want to enlarge the buffer for very long replacements. - Forgetting the trailing newline: The final
memcpycopies 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:
strstris case-sensitive. To match case-insensitively, lowercase both the line and the old word before comparing. - Missing
NULLchecks: Bothfopencalls 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 (
renameit tofilename.bak) before replacing, so the user can revert if needed. - For a more robust temp file, use
tmpfile()or generate a unique name withtmpnam()instead of hard-coding"temp.txt". - Compile with
gcc -Wall -Wextra -std=c11 -gto catch unused variables and format-string issues.