對於這種類型的替換(要替換的字符串的長度和替換字符串的長度是不同的長度),您通常需要從一個文件讀取數據,並將已更改的數據寫入其他文件。
您可以逐行閱讀文件,然後使用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