C - Replacing words

2019-06-14 22:32发布

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

标签: c stdin fgets
1条回答
冷血范
2楼-- · 2019-06-14 22:39

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.

查看更多
登录 后发表回答