You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改C代码实现无需用户输入自动替换文件指定单词?

修改后的C代码(内置替换规则)

以下是修改后的代码,已将替换规则直接写入代码中,仅需输入文件路径即可自动完成批量替换:

/**
 * C program to find and replace multiple predefined words in file.
 */

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

#define BUFFER_SIZE 1000

// 定义替换规则结构体
typedef struct {
    const char *oldWord;
    const char *newWord;
} Replacement;

/* 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];

    // 内置替换规则:可在此添加或修改替换对
    Replacement rules[] = {
        {"Hello", "Bye"},
        {"Morning", "Night"}
    };
    int numRules = sizeof(rules) / sizeof(rules[0]);


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


    /*  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 applying all replacement rules.
     */
    while ((fgets(buffer, BUFFER_SIZE, fPtr)) != NULL)
    {
        // 对当前行应用所有替换规则
        for (int i = 0; i < numRules; i++) {
            replaceAll(buffer, rules[i].oldWord, rules[i].newWord);
        }

        // 将替换后的内容写入临时文件
        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:\n");
    for (int i = 0; i < numRules; i++) {
        printf("- '%s' with '%s'\n", rules[i].oldWord, rules[i].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);
    }
}

关键修改点:

  • 新增Replacement结构体,用于存储替换规则的原单词和目标单词
  • 内置rules数组,直接定义所有需要替换的词对,可根据需求自行添加或修改
  • 移除了原代码中手动输入替换单词的逻辑,仅保留文件路径输入
  • 修改行处理逻辑,对每一行依次应用所有替换规则
  • 最终输出所有完成的替换规则列表

内容的提问来源于stack exchange,提问作者Maxv1n

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 01:05:02