luc097.c (2169B)
1 /* 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> 2 */ 3 /* Let Us C, Chap- 20 (More Issues In Input/Output), Qn No.: A(c) */ 4 5 /* This file is auto-generated by a bot. */ 6 /* This code is not compiled; it is for reference only. */ 7 8 9 #include <stdio.h> 10 #include <stdlib.h> 11 #include <string.h> 12 #include <ctype.h> 13 14 void replace_all(char *str, const char *old_w, const char *new_w, FILE *ft); 15 16 int main(int argc, char *argv[]) 17 { 18 FILE *fp, *ft; 19 char line[1000]; 20 char *old_word, *new_word, *filename; 21 22 if (argc != 4) 23 { 24 printf("Usage: %s <old word> <new word> <filename>\n", argv[0]); 25 exit(1); 26 } 27 28 old_word = argv[1]; 29 new_word = argv[2]; 30 filename = argv[3]; 31 32 fp = fopen(filename, "r"); 33 if (fp == NULL) 34 { 35 printf("Error opening file: %s\n", filename); 36 exit(2); 37 } 38 39 // Create a temporary file 40 ft = fopen("temp.tmp", "w"); 41 if (ft == NULL) 42 { 43 printf("Error creating temporary file.\n"); 44 fclose(fp); 45 exit(3); 46 } 47 48 // Process line by line 49 while (fgets(line, sizeof(line), fp)) 50 { 51 replace_all(line, old_word, new_word, ft); 52 } 53 54 fclose(fp); 55 fclose(ft); 56 57 // Replace original file with updated file 58 remove(filename); 59 rename("temp.tmp", filename); 60 61 printf("Replacement complete.\n"); 62 63 return 0; 64 } 65 66 void replace_all(char *str, const char *old_w, const char *new_w, FILE *ft) 67 { 68 char *pos, temp[1000]; 69 int index = 0; 70 int old_len = strlen(old_w); 71 72 /* We cannot easily modify 'str' in place because new_w 73 might be larger than old_w. We write directly to file. 74 */ 75 76 while ((pos = strstr(str, old_w)) != NULL) 77 { 78 // Write everything before the match 79 while (str < pos) 80 { 81 fputc(*str, ft); 82 str++; 83 } 84 85 // Write the new word 86 fputs(new_w, ft); 87 88 // Skip the old word in the source string 89 str += old_len; 90 } 91 92 // Write the remainder of the line 93 fputs(str, ft); 94 }