开发者

fread returns zero

开发者 https://www.devze.com 2023-01-09 13:13 出处:网络
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

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;
}

Any takers?


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.


If fread returns zero, then either of End-of-file or an Error occurred.

RETURN VALUE

fread() and fwrite() return the number of items successfully read or written (i.e., not the number of characters). If an error occurs, or the end-of-file is reached, the return value is a short item count (or zero).

fread() does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred.

I suggest you should check for errors on the file, and if an error occurred, you should print the relevant error message to get more information! This should be part of both your current debugging but also of the finished code as error handling.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号