如果新舊值的字符數是相同的(你的情況),您可以覆蓋它們:
FILE* fp = fopen("x.txt", "r+"); // note: r+, not rw
char row[256];
char* string = "\"jacket\":"; // note: contains punctuation
char* newvalue = "42\n"; // note: contains a line break
while (!feof(fp)) // note: feof is bad style
{
long pos = ftell(fp);
fgets(row, 256, fp); // note: might add error handling
// check if there is the "jacket": in this row,
if (strncmp(row, string, strlen(string)) == 0)
{
// check that the old length is exactly the same as the new length
// note: assumes the row contains a line-break \n
if (strlen(row) == strlen(string) + strlen(newvalue))
{
// then edit the row
fseek(fp, (long)(pos + strlen(string)), SEEK_SET);
fputs(newvalue, fp);
fseek(fp, (long)(pos + strlen(string) + strlen(newvalue)), SEEK_SET);
}
else
{
printf("Too bad, cannot change value");
}
}
}
fclose(fp);
你可能想改變你的文件格式,包括填充,例如:
"shoes":12____
"pants":33____
"jacket":26____
"glasses":16____
"t-shirt":182___
這裏_
可視化空間字符;這種文件格式最多支持999999項。如果你做了這樣的改變,你需要改變上面的代碼來檢查和調整空格的數量等。
在C++中是否有最簡單的解決方案? – xRobot 2012-04-19 10:02:20
@xRobot語言無所謂,問題和解決方案是一樣的。 – 2012-04-19 10:09:39
爲什麼我們不能在「r +」模式下打開文件並使用'ftell','fseek'組合並覆蓋文件? – 2012-04-19 10:13:47