将文本文件中的模式"find"替换为"replace"作为输入和输出文件的 C 程序应具有替换的模式



我在网上搜索了一下,但没有得到如何做到这一点的确切想法,因为m能够编写的代码只是针对该模式的一次出现,但如果该模式有不同的出现行??

如果您在Unix或类似系统(如Linux或MacOS X)上,那么您已经有了一个命令行程序来执行此操作:sed

否则,您必须从原始文件中读取并写入新文件,在读取和写入时替换文本。之后,您必须将新文件重命名为旧的原始文件。

至于文本的实际查找,如果它是一个固定的字符串,您可以使用例如strstr,从其他方面查看正则表达式。

编辑:如何使用sed(1):

$ sed -i 's/xyz/abc/g' infile.txt

上述命令将读取infile.txt,用abc替换所有出现的文本xyz,并将其写回infile.txt

编辑:如何搜索/替换:

FILE *input = fopen("input.txt", "r");
FILE *output = fopen("temp.txt", "w");
char buffer[512];
while (fgets(buffer, sizeof(buffer), input) != NULL)
{
    /* The text to find */
    static const char text_to_find[] = "xyz";
    /* The text to replace it with */
    static const char text_to_replace[] = "abc";
    char *pos = strstr(buffer, text_to_find);
    if (pos != NULL)
    {
        /* Allocate memory for temporary buffer */
        char *temp = calloc(
            strlen(buffer) - strlen(text_to_find) + strlen(text_to_replace) + 1, 1);
        /* Copy the text before the text to replace */
        memcpy(temp, buffer, pos - buffer);
        /* Copy in the replacement text */
        memcpy(temp + (pos - buffer), text_to_replace, strlen(text_to_replace));
        /* Copy the remaining text from after the replace text */
        memcpy(temp + (pos - buffer) + strlen(text_to_replace),
               pos + strlen(text_to_find),
               1 + strlen(buffer) - ((pos - buffer) + strlen(text_to_find)));
        fputs(temp, output);
        free(temp);
    }
    else
        fputs(buffer, output);
}
fclose(output);
fclose(input);
/* Rename the temporary file to the original file */
rename("input.txt", "temp.txt");

此代码已经过工作测试。

注意:如果你不知道指针算术是什么,那么上面的代码可能很难理解,你只需要相信我,它会做它应该做的。:)

最新更新