C - Replacing words

与世无争的帅哥 提交于 2019-12-10 12:35:02

问题


My goal here is to read text from a file redirected from stdin, then replace certain argv passed words with the word "Replaced".

For example, if I run:

$ ./a.exe line < input.txt

where input.txt is "Test line one", at the end I should print "Test Replaced one." I'm not quite sure where my code is going wrong, sometimes I get segmentation fault, and I'm also not sure how I would go about printing the newOut string, or if I even need one.

As a side note, if I was reading using fgets, what if the 59th character started "li" then as it started reading again as the 0th index for the next read command, "ne". Wouldn't that not count as one string for strstr to search?

Any help is appreciated, thanks

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

int main(int argc, char** argv) {

    char fileRead[60];  
    char newOut[];
    while (!feof(stdin)){ 
        fgets(fileRead,60,stdin); //read file 60 characters at a time
        if (strstr(fileRead,argv[1])){ // if argumentv[1] is contained in fileRead
            strncpy(newOut, fileRead, strlen(argv[1])); // replace 
        }        
    }

        return (0);
}

回答1:


As I observed in the comments to your previous question, C — A better method for replacing:

An obvious suggestion is to read whole lines with fgets() and then search those (maybe with strstr()) to find the word to be replaced, and then print the material before the word and the replacement text before resuming the search from after the matched word in the line (so [given "test" as argv[1]] a line containing "testing, 1, 2, 3, tested!" ends up as "Replaced!ing, 1, 2, 3, Replaced!ed!".

This is a rather straight-forward implementation of the described algorithm.

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

int main(int argc, char **argv)
{
    assert(argc > 1);
    char fileRead[4096];  /* Show me a desktop computer where this causes trouble! */
    char replace[] = "Replaced!"; 
    size_t word_len = strlen(argv[1]);

    while (fgets(fileRead, sizeof(fileRead), stdin) != 0)
    {
        char *start = fileRead;
        char *word_at;
        while ((word_at = strstr(start, argv[1])) != 0)
        {
            printf("%.*s%s", (int)(word_at - start), start, replace);
            start = word_at + word_len;
        }
        printf("%s", start);
    }

    return (0);
}

Note that the position of the assert() makes this C99 code; place it after the definition of word_len and it becomes C89 code.



来源:https://stackoverflow.com/questions/26186734/c-replacing-words

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!