C语言,fread函数读取二进制文件时抛出异常

问题描述 投票:0回答:1

该函数接收命令行参数中的main.c二进制文件路径,然后读取这个文件的内容,放入缓冲区字符数组中,在末尾添加结束符'',转换为字符串并返回.

static char* readFile(const char* path) {
    FILE* file = fopen(path, "rb");
    if (!file) {
        fprintf(stderr, "Could not open file \" %s \".\n", path);
        exit(1);
    }

    fseek(file, 0L, SEEK_END);
    size_t fileSize = ftell(file);
    rewind(file);

    char* buffer = (char*)malloc(sizeof(char) * (fileSize + 1));
    if (!buffer) {
        fprintf(stderr, "Not enought memory to read \%s\".\n", path);
        exit(1);
    }

    size_t bytesRead = fread(buffer, sizeof(char), fileSize, file); // ERROR!!!

    if (bytesRead < fileSize) {
        fprintf(stderr, "Could not read file \"%s\".\n", path);
        exit(1);
    }
    buffer[bytesRead] = '\0';
    
    fclose(file);
    return buffer;
}

导致异常的语句:size_t bytesRead = fread(buffer, sizeof(char), fileSize, file);

fread 函数在读取二进制文件时抛出异常。我尝试强制对 fileSize 进行类型转换,但这似乎不是类型问题。 fileSize可以正确接收文件的字节数。我真的不知道如何纠正。

c file fopen fread fseek
1个回答
0
投票
fseek(file, 0L, SEEK_END);
size_t fileSize = ftell(file);
rewind(file);

二进制流不需要支持

SEEK_END
值,并且
fseek()
语句在 ISO C 标准中被指定为具有未定义的行为。

除此之外,C 没有例外。

fread()
无法引发异常。

© www.soinside.com 2019 - 2024. All rights reserved.