我有一个这样的txt文件:
"shoes":12
"pants":33
"jacket":26
"glasses":16
"t-shirt":182
Run Code Online (Sandbox Code Playgroud)
我需要编辑夹克的数量(例如从26到42).所以,我已经编写了这段代码,但我不知道如何编辑一个特定的行,其中有"jacket"这个词:
#include <stdio.h>
int main() {
char row[256];
FILE *fp;
if (!(fp=fopen("myfile.txt","rw"))) {
printf("Error");
return 1;
}
while (!feof(fp)){
fgets(row, 256, fp);
// if there is the "jacket" in this row, then edit the row
}
fclose (fp);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,没有简单的解决方案.
常见的方法是将所有行(已修改或未修改)写入临时文件,然后将临时文件移动到现有文件上.