对于这种类型的替换(要替换的字符串的长度和替换字符串的长度是不同的长度),您通常需要从一个文件读取数据,并将已更改的数据写入其他文件。
您可以逐行阅读文件,然后使用sscanf()
来确定该行是否需要更换。
例如:
#include <string.h>
#include <stdio.h>
int main()
{
FILE *input = fopen("in.txt", "r");
FILE *output = fopen("out.txt", "w");
char target[] = "C45";
char replacement[] = "X4534";
char lineBuffer[100];
while (fgets(lineBuffer, sizeof lineBuffer, input) != NULL)
{
char procedure[10];
if (sscanf(lineBuffer, "The procedure at %9s", procedure) == 1)
{
if (strcmp(procedure, target) == 0)
{
// if we get here, then the line matched the format we're
// looking for and we can therefore write our replacement
// line instead.
fprintf(output, "The procedure at %s is incomplete\n", replacement);
continue;
}
}
// if we get to this point, then the line didn't match the format
// or the procedure didn't match the one we're looking for, so we
// just output the line as it is.
fputs(lineBuffer, output);
}
fclose(input);
fclose(output);
}
上面的代码应该给你一个什么样的介入了一些想法。一旦你已经out.txt
保存,您可以使用标准的C函数rename()
,例如:
rename("out.txt", "in.txt");
在C中没有真正的“替换”功能超过
in.txt
上面移动它,你需要覆盖所有下面的话。 – moeCake您应该从原始文件读取,转换,写入临时文件,然后将临时文件重命名为原始文件。覆盖也可以,但是在更换之后需要移动内容时,逻辑会有点混乱。 – Hang