luc097.c ​
Metadata ​
- Author — Amit Dutta
- Last updated — 08 Feb 2026
- License — MIT License (See the LICENSE file for details)
Problem Statement ​
Problem Statement
Write a program using command-line arguments to search for a word in a file and replace it with the specified word.\nUsage: change <old word> <new word> <filename>
Source Code ​
Printing the code
To print this file, open it on GitHub and click Raw before printing, or use the Download Raw button above and print directly from that page.
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void replace_all(char *str, const char *old_w, const char *new_w, FILE *ft);
int main(int argc, char *argv[])
{
FILE *fp, *ft;
char line[1000];
char *old_word, *new_word, *filename;
if (argc != 4)
{
printf("Usage: %s <old word> <new word> <filename>\n", argv[0]);
exit(1);
}
old_word = argv[1];
new_word = argv[2];
filename = argv[3];
fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Error opening file: %s\n", filename);
exit(2);
}
// Create a temporary file
ft = fopen("temp.tmp", "w");
if (ft == NULL)
{
printf("Error creating temporary file.\n");
fclose(fp);
exit(3);
}
// Process line by line
while (fgets(line, sizeof(line), fp))
{
replace_all(line, old_word, new_word, ft);
}
fclose(fp);
fclose(ft);
// Replace original file with updated file
remove(filename);
rename("temp.tmp", filename);
printf("Replacement complete.\n");
return 0;
}
void replace_all(char *str, const char *old_w, const char *new_w, FILE *ft)
{
char *pos, temp[1000];
int index = 0;
int old_len = strlen(old_w);
/* We cannot easily modify 'str' in place because new_w
might be larger than old_w. We write directly to file.
*/
while ((pos = strstr(str, old_w)) != NULL)
{
// Write everything before the match
while (str < pos)
{
fputc(*str, ft);
str++;
}
// Write the new word
fputs(new_w, ft);
// Skip the old word in the source string
str += old_len;
}
// Write the remainder of the line
fputs(str, ft);
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86