/* * Author : Amit Dutta * Date : 08 Feb 2026 * Repo : https://github.com/notamitgamer/bsc * License : MIT License (See the LICENSE file for details) */ /* Write a program using command-line arguments to search for a word in a file and replace it with the specified word.\nUsage: change */ /* Let Us C, Chap- 20 (More Issues In Input/Output), Qn No.: A(c) */ /* This file is auto-generated by a bot. */ /* This code is not compiled; it is for reference only. */ #include #include #include #include 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 \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); }