C program to replace a pattern “find” with “replac

2019-07-31 18:55发布

i searched on net but not getting the exact idea of how to do it as the code m being able to write is just for a single occurence of the pattern but if there are different lines of occurence of that pattern??

标签: c replace
1条回答
疯言疯语
2楼-- · 2019-07-31 19:22

If you are on a Unix or similar system (like Linux or MacOS X) then you already have a command line program to do this: sed.

Otherwise you have to read from the original file and write to a new file, replacing the text while reading and writing. After that you have to rename the new file as the old original file.

As for the actual finding of the text, if it's a fixed string you can use e.g. strstr, other wise look into regular expressions.

Edit: How to do it with sed(1):

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

The above command will read infile.txt, replace all occurrences of the text xyz with abc and write it back to infile.txt.

Edit: How to search/replace:

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");

This code has been tested to work.

Note: If you don't know what pointer arithmetic is, then the above code might be very hard to follow and understand, and you just have to trust me that it does what it should. :)

查看更多
登录 后发表回答