You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用stdio.h覆盖文件内容?ab模式+fseek为何无法生效?

为什么用ab模式打开文件后fseek无法覆盖内容?

这是C标准对**追加模式(a/ab)**的硬性规定:当文件以追加模式打开时,所有后续的写操作都会自动将文件指针定位到文件末尾,完全不受你之前fseek设置的位置影响。你看到的ftell返回0只是fseek执行后的临时状态,但一旦调用fputc,系统就会强制把指针移到末尾再写入,这就是为什么每次写入后位置跳到了11、12...

要实现覆盖前5个字节的需求,你需要用读写模式打开文件,而不是追加模式。合适的模式是rb+(二进制读写,文件必须已存在,不会截断原有内容),wb+会先清空文件,这里不适用,因为你要保留后面的字节。

修改后的代码如下:

#include <stdio.h>

int main()
{
    FILE *f;
    unsigned char ba;
    int i;

    f = fopen("junk", "wb");
    for (i = 1; i <= 10; i++)
        fputc(i, f);
    fclose(f);
    // 将ab模式改为rb+模式
    f = fopen("junk", "rb+");
    fseek(f, 0, SEEK_SET);

    for (i = 1; i <= 5; i++) {
        printf("Position before: %ld\n", ftell(f));
        fputc(99, f);
        printf("Position after: %ld\n", ftell(f));
    }

    fclose(f);
    f = fopen("junk", "rb");

    for (i = 1; i <= 10; i++) { 
        ba = fgetc(f);
        printf("%d ", ba); 
    }

    printf("\n");
}

运行后会得到你预期的结果:

Position before: 0
Position after: 1
Position before: 1
Position after: 2
Position before: 2
Position after: 3
Position before: 3
Position after: 4
Position before: 4
Position after: 5
99 99 99 99 99 6 7 8 9 10

简单总结下几种模式的核心区别:

  • ab:只能写,且所有写操作强制在文件末尾,无法覆盖已有内容
  • rb+:可读写,文件必须存在,读写位置可通过fseek自由控制,写操作会覆盖当前位置的字节
  • wb+:可读写,会先清空文件原有内容,适合需要重新写入整个文件的场景

内容的提问来源于stack exchange,提问作者Scott Franco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 15:05:31