如何搜索字符串并替换文本文件中的字符串?

时间:2014-03-14 11:49:33

标签: c

我在替换文本文件中的字符串时遇到问题。下面的函数能够找到字符串。我想替换文字,但我不知道该怎么做。

这是我的代码:

void searchchangeword() {
    //Related to file status 

    char buffer[1024]= {0};
    FILE *stream;
    char *Ptr,*Ptr2;
    int len;
    int pos;
    stream = fopen("input.txt", "r");
    if(NULL == stream)
         printf("fopen failed");

    while(1) {
        fscanf(stream,"%s",buffer);
        if((strcmp(buffer,"LogLevel")== 0)) {
            pos = ftell(stream);
            memset(buffer,0,sizeof(buffer));
            fgets(buffer,sizeof(buffer),stream);
            // Here i get the word i want to replace
            fscanf(stream,"%s",buffer);
            break;
        }
        else
            continue;
    }
    // closing the Opening file
    if((Ptr2 = strchr(buffer,'\n')) != NULL)
        *Ptr2 = 0;
    Ptr = strtok(buffer, " ");
    // Suppose Ptr contains John 
    // How can i replace it with James at the same position
    //-- Changing string logic ??
}

1 个答案:

答案 0 :(得分:0)

我会告诉你这个想法,而不是代码。

一个简单的方法是:

  • 将文件加载到字符串中(char * text)(使用fopen,malloc,readf,fseek,ftell)

  • 将另一个文件作为目标文件(使用fopen),并以write形式打开

  • 再创建两个字符串(string1,string2)并在string1中加载该文件 直到pos(要替换的单词的位置)(使用文本)然后加载 在string2中来自pos +你想要替换的字符串的长度 直到文件结束(使用文本)。所以string1将一直到 “LogLevel”和“LogLevel”之后的string2。(如果“LogLevel”是要替换的字符串)

  • 然后在目标文件中写下第一个字符串(string1) 替换单词和第二个字符串(string2)(全部在 目的地文件)

  • 关闭所有文件(使用fclose)

  • 删除原始文件(“input.txt”)(使用删除)

  • 将目标文件重命名为原始文件“input.txt” 案例(使用重命名)

这就是我在愚蠢的大脑中的想法。也许那是有帮助的。

相关问题