fread返回零 [英] fread returns zero

查看:69
本文介绍了fread返回零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将rom文件读入内存并自动分配以适合该文件的函数,但是每次我尝试从文件描述符中读取时,fread()都会返回零.我不确定自己在做什么错.有人可以帮忙吗?

I have a function that reads a rom file into memory and automatically allocates to fit the file but every time I try to read from the file descriptor, fread() returns zero. I'm unsure what I'm doing wrong. can anybody help?

int read_rom(const char *filename, unsigned char ***rom) {
    int rom_size;
    FILE *fd = NULL;

    if((fd = fopen(filename, "r")) != NULL) {
        fseek(fd, 0, SEEK_END);
        rom_size = ftell(fd);
        (*rom) = malloc(rom_size);
        int read = fread(rom, 1, rom_size, fd);
        fclose(fd);

        printf("read: %d\n", read);

        return rom_size;
    }

    return -1;
}

int main(int argc, char **argv) {
    unsigned char rom_size = 0;
    unsigned char **rom = NULL;
    rom_size = read_rom(argv[1], &rom);

    return 1;
}

有没有人?

推荐答案

您没有读取任何内容,因为您 feek> 到了文件的末尾.在执行 fread 之前,先执行 fseek(fd,0,SEEK_SET); 返回文件的开头.

You aren't reading anything in because you fseeked to the end of the file. Do a fseek(fd, 0, SEEK_SET); to return to the beginning of the file before you fread.

这篇关于fread返回零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆