Skip to content

luc097.c

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

Metadata

Property Detail
Author Amit Dutta amitdutta4255@gmail.com
Date 08 Feb 2026
License MIT License (See the LICENSE file for details)

Actions

Raw View on GitHub

💡 You can print or save this file by opening Raw and using your browser.

Source Code

#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);
}