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

读取文件时出现溢出问题求助:获取文件大小仍读取越界

文件读取溢出问题排查与解决

问题根源

你遇到的问题核心是文本模式打开文件导致的换行符转换差异:

  • 用"r"文本模式打开文件时,Windows系统会把文件里的\r\n(CRLF)换行符转换为单个\n(LF)。这就导致ftell返回的是文件实际字节数(包含\r的字节),但fread读取的是转换后的字符数(少了\r对应的字节)。缓冲区里未被fread覆盖的区域就会残留垃圾数据(也就是你看到的=)。
  • 另外你的错误输出写法有问题:"Error whilst reading file: " + error_no是指针偏移操作,会导致字符串被错误截断,应该用<<来拼接输出。

修正后的代码

#include <cstdio>
#include <iostream>
#include <cstdlib>

int main(const char* filepath) {
    FILE* file;
    int error_no = fopen_s(&file, filepath, "rb"); // 用二进制模式打开

    if (error_no != 0 || file == nullptr) {
        std::cout << "Error whilst reading file: " << error_no << std::endl;
        return 1;
    }

    // 获取文件大小
    fseek(file, 0, SEEK_END);
    size_t size = ftell(file);
    if (size == -1) {
        std::cout << "Failed to get file size" << std::endl;
        fclose(file);
        return 1;
    }

    // 分配缓冲区,检查是否成功
    char* fileAsString = (char*)malloc(size + 1);
    if (!fileAsString) {
        std::cout << "Memory allocation failed" << std::endl;
        fclose(file);
        return 1;
    }

    // 重置文件指针并读取内容
    fseek(file, 0, SEEK_SET);
    size_t read_bytes = fread(fileAsString, 1, size, file);
    if (read_bytes != size) {
        std::cout << "Only read " << read_bytes << " bytes out of " << size << std::endl;
        free(fileAsString);
        fclose(file);
        return 1;
    }

    // 添加字符串结束符
    fileAsString[size] = '\0';

    std::cout << size << std::endl;
    std::cout << fileAsString << std::endl;

    // 释放资源
    free(fileAsString);
    fclose(file);
    return 0;
}

关键修正点

  • 二进制模式打开文件:用"rb"替代"r",这样系统不会对文件内容做任何转换,ftell返回的字节数和fread读取的字节数完全一致,避免缓冲区残留垃圾数据。
  • 修复错误输出:用std::cout << "Error..." << error_no替代指针偏移写法,确保错误信息正确输出。
  • 增加内存分配检查:malloc可能失败,必须检查返回值,避免空指针操作。
  • 检查fread返回值:确认实际读取的字节数和预期一致,避免读取不完整的情况。
  • 释放内存:使用完缓冲区后用free释放,防止内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 22:05:20