如何修改我的C代码以在无用户输入的情况下替换文件中的单词?

huangapple go评论53阅读模式
英文:

How can I modify my C code to replace words in a file without user input?

问题

/**
 * 在文件中查找并替换所有单词出现的C程序。
 */

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

#define BUFFER_SIZE 1000

/* 函数声明 */
void replaceAll(char *str, const char *oldWord, const char *newWord);

int main()
{
    /* 用于保存输入文件的文件指针 */
    FILE *fPtr;
    FILE *fTemp;
    char path[100];

    char buffer[BUFFER_SIZE];
    char oldWord[100], newWord[100];

    printf("输入源文件的路径:");
    scanf("%s", path);

    /* 要替换的单词 */
    strcpy(oldWord, "Hello");
    strcpy(newWord, "Bye");

    /* 打开所需的所有文件 */
    fPtr = fopen(path, "r");
    fTemp = fopen("replace.tmp", "w");

    /* 如果无法以给定模式打开文件,则fopen()返回NULL。 */
    if (fPtr == NULL || fTemp == NULL)
    {
        /* 无法打开文件,因此退出 */
        printf("\n无法打开文件。\n");
        printf("请检查文件是否存在以及您是否具有读/写权限。\n");
        exit(EXIT_SUCCESS);
    }

    /*
     * 从源文件中读取行并在替换给定单词后写入目标文件。
     */
    while (fgets(buffer, BUFFER_SIZE, fPtr) != NULL)
    {
        // 从当前行替换所有出现的单词
        replaceAll(buffer, oldWord, newWord);

        // 替换后将其写入临时文件。
        fputs(buffer, fTemp);
    }

    /* 关闭所有文件以释放资源 */
    fclose(fPtr);
    fclose(fTemp);

    /* 删除原始源文件 */
    remove(path);

    /* 将临时文件重命名为原始文件 */
    rename("replace.tmp", path);

    printf("\n成功替换了所有出现的'%s'为'%s'。\n", oldWord, newWord);

    return 0;
}

/**
 * 在字符串中替换给定单词的所有出现。
 */
void replaceAll(char *str, const char *oldWord, const char *newWord)
{
    char *pos, temp[BUFFER_SIZE];
    int index = 0;
    int owlen;

    owlen = strlen(oldWord);

    // 修复:如果oldWord和newWord相同,它会陷入无限循环
    if (!strcmp(oldWord, newWord))
    {
        return;
    }

    /*
     * 重复,直到所有出现都被替换。
     */
    while ((pos = strstr(str, oldWord)) != NULL)
    {
        // 备份当前行
        strcpy(temp, str);

        // 当前找到的单词的索引
        index = pos - str;

        // 在找到的单词索引后终止字符串
        str[index] = '\0';

        // 将字符串与新单词连接
        strcat(str, newWord);

        // 在oldword找到的索引后将字符串与剩余的单词连接。
        strcat(str, temp + index + owlen);
    }
}

这个修改后的代码将替换指定路径的源文件中的所有 "Hello" 为 "Bye"。您可以根据需要自行更改要替换的单词,然后只需提供源文件的路径即可。

英文:
/**
* C program to find and replace all occurrences of a word in file.
*/
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;
#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(&quot;Enter path of source file: &quot;);
scanf(&quot;%s&quot;, path);
printf(&quot;Enter word to replace: &quot;);
scanf(&quot;%s&quot;, oldWord);
printf(&quot;Replace &#39;%s&#39; with: &quot;);
scanf(&quot;%s&quot;, newWord);
/*  Open all required files */
fPtr  = fopen(path, &quot;r&quot;);
fTemp = fopen(&quot;replace.tmp&quot;, &quot;w&quot;); 
/* fopen() return NULL if unable to open file in given mode. */
if (fPtr == NULL || fTemp == NULL)
{
/* Unable to open file hence exit */
printf(&quot;\nUnable to open file.\n&quot;);
printf(&quot;Please check whether file exists and you have read/write privilege.\n&quot;);
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(&quot;replace.tmp&quot;, path);
printf(&quot;\nSuccessfully replaced all occurrences of &#39;%s&#39; with &#39;%s&#39;.&quot;, 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] = &#39;\0&#39;;
// Concatenate str with new word 
strcat(str, newWord);
// Concatenate str with remaining words after 
// oldword found index.
strcat(str, temp + index + owlen);
}
}

I have that code in C which can change all "oldWords" into "newWords". Works fine, but everytime I want to change the code to change the words on its own I'm completely stupid. I want that I don't have to put the words that have to change into the console, but I want to have them in the code. I just want to tell the console the path of the source file and that's it.

Would be nice if you could help me with some examples like Hello to Bye and Morning to Night.

答案1

得分: 1

如果您不想从用户输入中获取 oldWordnewWord,您可以在代码中将它们定义为常量:

const char* oldWord = "Hello";
const char* newWord = "Bye";
英文:

If you don't want to take oldWord and newWord from user input, you can define them as constants in the code:

const char* oldWord = &quot;Hello&quot;;
const char* newWord = &quot;Bye&quot;;

huangapple
  • 本文由 发表于 2023年6月1日 20:55:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76382116.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定