如何修改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
相关产品推荐
相关产品推荐

