Here is a code which is giving a user an ability to replace a word in another file but I want to replace a word in the same file. Whenever a user enters a word to replace, the word should be replaced in the same file. How to do this?
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
void findAndReplaceInFile() { 
    FILE *fr, *fw; 
    char word[100], ch, read[100], replace[100];  
    fr = fopen("file.txt", "r"); 
    fw = fopen("new.txt", "w"); 
    if (fr == NULL || fw == NULL) { 
        printf("Can't open file."); 
        exit(0); 
    } 
    printf("Enter the word to find: "); 
    fgets(word, 100, stdin); 
    word[strlen(word) - 1] = word[strlen(word)]; 
    printf("Enter the word to replace it with: "); 
    fgets(replace, 100, stdin); 
    rewind(fr); 
    while (!feof(fr)) { 
        fscanf(fr, "%s", read); 
        if (strcmp(read, word) == 0) { 
            strcpy(read, replace); 
        } 
        fprintf(fw, "%s ", read); 
    } 
    fclose(fr); 
    fclose(fw); 
} 
int main() { findAndReplaceInFile(); } 
 
    