C program to find and replace a word in file

Quick links

Write a C program to find and replace all occurrences of a word in file. How to find and replace a word in file in C programming. Logic to replace all occurrences of a word in file in C program.

Required knowledge

Basic Input Output, String, File Handling

Logic to find and replace a word in file

Step by step descriptive logic to find and replace all occurrences of a word in file.

  1. Open source file in r (read) mode, store its reference to fptr.
  2. Create a temporary file fTemp in w (write) mode. Store its reference to fTemp.
  3. Input old word and new word to replace, from user. Store both in oldWord and newWord respectively.
  4. Read a line from source file, store line read in str.
  5. Find next occurrence of oldWord in str, store its reference in some variable say pos.
  6. Copy string str to a temporary variable say temp.
  7. Find index of first occurrence of oldWord in str using pointer arithmetic index = pos - str.
  8. Mark index at which first occurrence of oldWord is found as string termination with NULL character. Use str[index] = '\0';.
  9. Concatenate string str with new word to replace with, say strcat(str, newWord);.
  10. Concatenate string str with remaining words after old word to replace, say strcat(str, temp + index + owlen);. Where owlen is length of oldWord string.
  11. Repeat steps 5-10 till occurrence of oldWord is found in str. Otherwise goto step 12.
  12. Write string str to file fTemp.
  13. Repeat step 3 till end of source file.
  14. Close all files to save changes.
  15. Delete source file and rename fTemp as source file path.

Program to find and replace a word in file

/**
 * C program to find and replace all occurrences of a word in file.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE 1000

/* Function declaration */
void replaceAll(char *str, const char *oldWord, const char *newWord);


int main()
{
    /* File pointer to hold reference of input file */
    FILE * fPtr;
    FILE * fTemp;
    char path[100];
    
    char buffer[BUFFER_SIZE];
    char oldWord[100], newWord[100];


    printf("Enter path of source file: ");
    scanf("%s", path);

    printf("Enter word to replace: ");
    scanf("%s", oldWord);

    printf("Replace '%s' with: ");
    scanf("%s", newWord);


    /*  Open all required files */
    fPtr  = fopen(path, "r");
    fTemp = fopen("replace.tmp", "w"); 

    /* fopen() return NULL if unable to open file in given mode. */
    if (fPtr == NULL || fTemp == NULL)
    {
        /* Unable to open file hence exit */
        printf("\nUnable to open file.\n");
        printf("Please check whether file exists and you have read/write privilege.\n");
        exit(EXIT_SUCCESS);
    }


    /*
     * Read line from source file and write to destination 
     * file after replacing given word.
     */
    while ((fgets(buffer, BUFFER_SIZE, fPtr)) != NULL)
    {
        // Replace all occurrence of word from current line
        replaceAll(buffer, oldWord, newWord);

        // After replacing write it to temp file.
        fputs(buffer, fTemp);
    }


    /* Close all files to release resource */
    fclose(fPtr);
    fclose(fTemp);


    /* Delete original source file */
    remove(path);

    /* Rename temp file as original file */
    rename("replace.tmp", path);

    printf("\nSuccessfully replaced all occurrences of '%s' with '%s'.", oldWord, newWord);

    return 0;
}



/**
 * Replace all occurrences of a given a word in string.
 */
void replaceAll(char *str, const char *oldWord, const char *newWord)
{
    char *pos, temp[BUFFER_SIZE];
    int index = 0;
    int owlen;

    owlen = strlen(oldWord);

    // Fix: If oldWord and newWord are same it goes to infinite loop
    if (!strcmp(oldWord, newWord)) {
        return;
    }


    /*
     * Repeat till all occurrences are replaced. 
     */
    while ((pos = strstr(str, oldWord)) != NULL)
    {
        // Backup current line
        strcpy(temp, str);

        // Index of current found word
        index = pos - str;

        // Terminate str after word found index
        str[index] = '\0';

        // Concatenate str with new word 
        strcat(str, newWord);
        
        // Concatenate str with remaining words after 
        // oldword found index.
        strcat(str, temp + index + owlen);
    }
}

Suppose if <strong>data/file3.txt</strong> contains.

I love programming.
I am learning C programming at Codeforwin.
Programming with files is fun.
Learning C programming at Codeforwin is simple and easy.
 

Output

 
 
 

 

Enter path of source file: data/file3.txt
Enter word to replace: is
Replace 'is' with: izzzz

Successfully replaced all occurrences of 'is' with 'izzzz'.

 

After executing this program contents of <strong>data/file3.txt</strong>.

I love programming.
I am learning C programming at Codeforwin.
Programming with files izzzz fun.
Learning C programming at Codeforwin izzzz simple and easy.

Happy coding 😉