编辑文件中的特定行

xRo*_*bot 1 c

我有一个这样的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)

Som*_*ude 5

不幸的是,没有简单的解决方案.

常见的方法是将所有行(已修改或未修改)写入临时文件,然后将临时文件移动到现有文件上.

  • @PavanManjunath可能,至少我们写的长度是_shorter或等于旧文本.如果它更长,我们将覆盖下一行的现有文本. (2认同)