C - 替换单词

时间:2014-10-03 20:58:52

标签: c stdin fgets

我的目标是从stdin重定向的文件中读取文本,然后用“替换”替换某些argv传递的单词。

例如,如果我跑:

$ ./a.exe line < input.txt

其中input.txt是“Test line one”,最后我应该打印“Test Replaced one”。 我不太确定我的代码出错了,有时我会出现分段错误,而且我也不确定如何打印newOut字符串,或者我是否需要一个字符串。

作为旁注,如果我正在使用fgets读取,如果第59个字符开始“li”,那么当它再次开始作为下一个读取命令的第0个索引“ne”时,该怎么办?这不会算作strstr搜索的一个字符串吗?

感谢任何帮助,谢谢

#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 个答案:

答案 0 :(得分:1)

正如我在上一个问题的评论中所指出的,C — A better method for replacing

  

一个明显的建议是用fgets()读取整行,然后搜索那些(可能带有strstr())以找到要替换的单词,然后在单词和替换文本之前打印材料在从行中匹配的单词之后恢复搜索之前(所以 [给定"test"作为argv[1]] ,包含"testing, 1, 2, 3, tested!"的行最终为{{1} }。

这是所描述算法的相当直接的实现。

"Replaced!ing, 1, 2, 3, Replaced!ed!"

请注意,#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); } 的位置构成了此C99代码;将它放在assert()的定义之后,它就变成了C89代码。