如果新旧值的字符数是相同的(你的情况),您可以覆盖它们:
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