A C program that reads a file, replaces every occurrence of a target word with a new word, and writes the result to a new file using standard file I/O functions (fopen, fgets, fputs, fclose).
#include <stdio.h>
#include <string.h>#define MAX_LINE 1024
#define MAX_WORD 100int main() {
FILE *in, *out;
char line[MAX_LINE];
char oldWord[MAX_WORD], newWord[MAX_WORD];printf("Enter word to replace: ");
scanf("%s", oldWord);
printf("Enter new word: ");
scanf("%s", newWord);in = fopen("input.txt", "r");
if (in == NULL) {
printf("Cannot open input.txt ");
return 1;
}out = fopen("output.txt", "w");
if (out == NULL) {
printf("Cannot open output.txt ");
fclose(in);
return 1;
}while (fgets(line, MAX_LINE, in) != NULL) {
char result[MAX_LINE] = "";
char *pos = line;
char *match;while ((match = strstr(pos, oldWord)) != NULL) {
strncat(result, pos, match - pos); // copy text before match
strcat(result, newWord); // copy replacement
pos = match + strlen(oldWord); // move past old word
}
strcat(result, pos); // copy remaining text
fputs(result, out);
}fclose(in);
fclose(out);printf("Replacement done. Check output.txt ");
return 0;
}
How It Works?
1.Headers —> stdio.h for file I/O, string.h for strstr, strcat, strncat, and strlen.
2.Input —> scanf("%s", oldWord) and scanf("%s", newWord) read the target and replacement words.
3.Open files —> fopen("input.txt", "r") opens the source for reading; fopen("output.txt", "w") creates/overwrites the destination.Both are checked for NULL to handle missing files.
4.Read line by line —> fgets(line, MAX_LINE, in) reads one line at a time into line.
5.Find & replace —> strstr(pos, oldWord) finds the next occurrence of the old word. Text before the match is copied with strncat, the new word is appended with strcat, and pos jumps past the old word.
6.Write output —> The modified line is written with fputs(result, out).
7.Close files —> fclose() flushes buffers and releases file handles.
Example
input.txt
I love cats. Cats are great. I have two cats.
Run:
Enter word to replace: cats
Enter new word: dogs
output.txt
I love dogs. Cats are great. I have two dogs.