文件读写模式 "r+" C 中的意外行为

File read write mode "r+" unexpected behavior in C

在下面的代码中,我正在搜索“.”。在我的模板中,在它后面粘贴一个字符串。出于某种原因,虽然字符串按预期粘贴,但它从我的模板中删除了一些文本。我不知道问题出在哪里。试过 fflush() 没有很好的效果。

#include <stdio.h>
#include <string.h>

int main() {
    FILE * fp;
    int tmp_char, tmp_offset;
    char file_name[50] = "FileIoTest_template.txt";
    char tmp_string1[50] = "Generic String 1";
    char tmp_string2[50] = "Generic String 2";
    long tmp_long;

    fp = fopen(file_name, "r+");
    //fseek(fp, 0, SEEK_SET);

    do {
        tmp_char = fgetc(fp);
        printf("%c ", tmp_char);
        if (tmp_char == '.')
           break;
    } while (tmp_char != EOF);
    tmp_long = ftell(fp);
    fseek(fp, tmp_long, SEEK_SET);
    tmp_offset = strlen(tmp_string1);
    fputs(tmp_string1, fp);
    fputs("\n", fp);
    //fflush(fp);

    fseek(fp, tmp_long+tmp_offset, SEEK_SET);
    do {
        tmp_char = fgetc(fp);
        printf("%c ", tmp_char);
        if (tmp_char == '.')
            break;
    } while (tmp_char != EOF);
    tmp_long = ftell(fp);
    fseek(fp, tmp_long, SEEK_SET);
    fputs(tmp_string2, fp);
    fputs("\n", fp);
    //fflush(fp);

    fclose(fp);
    return 0;
}

这是我的模板,"FileIoTest_template.txt":

Sample list:
1.
2.
3.
random text

4.
5.
6.

bunch of random text

我的代码的输出是:

Sample list:
1.Generic String 1
ext

4.Generic String 2
of random text

您不能通过在文件中间插入数据而不替换任何已经存在的内容来轻松修改文件。您需要覆盖整个文件,从插入点到结尾(经过 original 结尾到新结尾需要的任何点)。正确地这样做是很棘手的,而且尝试是不安全的,因为如果过程在中间中断那么你的文件就会被丢弃。

通常,人们会在临时文件中创建文件内容的新版本,一旦成功完成,就会用新文件替换原始文件。