C – 替换单词

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

例如,如果我运行:

$ ./a.exe line < input.txt 

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

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

任何帮助表示赞赏,谢谢

 #include  #include  #include  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 – 一种更好的替换方法 :

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

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

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

注意, assert()的位置构成了这个C99代码; 将它word_len的定义word_len ,它就变成了C89代码。