Dario Russo
Dario Russo

Reputation: 80

fread returns zero

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?

Upvotes: 2

Views: 7685

Answers (2)

u0b34a0f6ae
u0b34a0f6ae

Reputation: 49803

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.

Upvotes: 2

bta
bta

Reputation: 45057

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.

Upvotes: 13

Related Questions