如果旧值和新值中的字符数相同(您的情况),您可以覆盖它们:
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 个项目。如果你做这样的改变,你需要改变上面的代码来检查和调整空格的数量等。