C程序用文本文件中的“替换”替换模式“find”作为输入和输出文件应该具有替换模式

我在网上搜索但没有得到如何做到的确切想法,因为能够编写的代码只是单个出现的模式,但是如果有不同的模式出现?

如果您使用的是Unix或类似的系统(如Linux或MacOS X),那么您已经有了一个命令行程序来执行此操作: sed

否则,您必须从原始文件中读取并写入新文件,在读取和写入时替换文本。 之后,您必须将新文件重命名为旧的原始文件。

至于文本的实际发现,如果它是一个固定的字符串,你可以使用例如strstr ,其他明智的查看正则表达式 。

编辑:如何使用sed(1)

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

上面的命令将读取infile.txt ,用abc替换所有出现的文本xyz ,并将其写回infile.txt

编辑:如何搜索/替换:

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

此代码已经过测试可行 。

注意:如果您不知道指针算术是什么,那么上面的代码可能很难理解,您只需要相信我它应该做的事情。 🙂