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

Windows下C项目fread与ftell文件偏移异常问题求助

二进制文件读取偏移异常的原因及修复方案

核心问题:文本模式打开二进制文件

Windows系统中,用"r"模式打开文件属于文本模式,这种模式会自动处理行结束符:将文件中的\r\n(Windows标准换行)转换为内存中的\n。这会导致fread统计的读取字节数和实际文件指针偏移量不匹配——比如文件里的一个\r\n,文本模式下只算1个读取字节,但文件指针实际移动了2个字节,最终就会出现你看到的偏移量增长不符合预期的情况。

代码中的其他问题

  • fopen参数错误:正确调用应为myfile = fopen("你的文件名", "rb");,你写反了参数顺序,且未检查返回值(文件打开失败时myfile会为NULL,后续操作会触发崩溃)。
  • ftell返回值类型不匹配:ftell返回long类型,用int存储会在大文件场景下溢出,需改为long offset = ftell(myfile);。
  • 无循环终止条件:当fread返回0(文件读取完毕或出错)时,循环会无限执行,需添加退出逻辑。

修复后的代码

#include <stdio.h>
#include <stdint.h>
#include <errno.h>

int main()
{
    FILE* myfile;
    uint8_t buf[300];
    // 二进制模式打开文件,同时校验打开结果
    myfile = fopen("你的文件路径", "rb");
    if (myfile == NULL) {
        perror("文件打开失败");
        return 1;
    }

    while (1) {
        long offset = ftell(myfile);
        int read_cnt = fread(buf, 1, 256, myfile);
        printf("file offset = %ld\n", offset);
        printf("readcount = %d\n", read_cnt);

        // 读取完成或出错时退出循环
        if (read_cnt == 0) {
            break;
        }
    }

    fclose(myfile);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 17:14:54