用c替换文本中的2行而不是1行
我有一个搜索单词“Applicat”并替换整行的代码。现在我正试图让它搜索并替换两行,而不是一行,但我有一个小问题。下面是一个示例文本文件: 姓名:1234 应用:ft_链接 日期:今天 我希望脚本能够将文本文件更改为: 姓名:5678 申请者:无 日期:明天 到目前为止,我的代码工作,但它会重复应用程序行不止一次。。。我做错了什么?提前谢谢 这是我的密码:用c替换文本中的2行而不是1行,c,replace,line,C,Replace,Line,我有一个搜索单词“Applicat”并替换整行的代码。现在我正试图让它搜索并替换两行,而不是一行,但我有一个小问题。下面是一个示例文本文件: 姓名:1234 应用:ft_链接 日期:今天 我希望脚本能够将文本文件更改为: 姓名:5678 申请者:无 日期:明天 到目前为止,我的代码工作,但它会重复应用程序行不止一次。。。我做错了什么?提前谢谢 这是我的密码: FILE *input = fopen(buffer1, "r"); /* open file to read */ FILE
FILE *input = fopen(buffer1, "r"); /* open file to read */
FILE *output = fopen("temp.txt", "w");
char buffer[512];
while (fgets(buffer, sizeof(buffer), input) != NULL)
{
static const char text_to_find[] = "Applicat:"; /* String to search for */
static const char text_to_replace[] = "Applicat: None\n"; /* Replacement string */
static const char text_to_find2[] = "Name"; /* String to search for */
static const char text_to_replace2[] = "Name: 5678\n"; /* Replacement string */
char *pos = strstr(buffer, text_to_find);
if (pos != NULL)
{
fputs(text_to_replace, output);
}
char *pos2 = strstr(buffer, text_to_find2);
if (pos2 != NULL)
{
fputs(text_to_replace2, output);
}
else
fputs(buffer, output);
}
改变
为此:
char *pos = strstr(buffer, text_to_find);
if (pos != NULL)
{
fputs(text_to_replace, output);
}
char *pos2 = strstr(buffer, text_to_find2);
if (pos2 != NULL)
{
fputs(text_to_replace2, output);
}
if(pos==NULL && pos2==NULL)
fputs(buffer, output);
或者如果你更喜欢
char *pos = strstr(buffer, text_to_find);
char *pos2 = strstr(buffer, text_to_find2);
if(pos==NULL && pos2==NULL)
fputs(buffer, output);
if (pos2 != NULL)
fputs(text_to_replace2, output);
if (pos != NULL)
fputs(text_to_replace, output);
您刚刚错过了一个
其他:
char *pos = strstr(buffer, text_to_find);
char *pos2 = strstr(buffer, text_to_find2);
if (pos != NULL) {
fputs(text_to_replace, output);
} else if (pos2 != NULL) {
fputs(text_to_replace2, output);
} else
fputs(buffer, output);
char *pos = strstr(buffer, text_to_find);
char *pos2 = strstr(buffer, text_to_find2);
if (pos != NULL) {
fputs(text_to_replace, output);
} else if (pos2 != NULL) {
fputs(text_to_replace2, output);
} else
fputs(buffer, output);