Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fread() Returning Zero Bytes Read: I Don't Understand Why

I have looked through the man pages, and have read a few examples on line. All my other system and standard calls seem to be working around the same data, why not fread?

#include <stdlib.h>
#include <stdio.h>

unsigned char *data;

int main(int argc, char *argv[])
{
    FILE *fp = fopen("test_out.raw", "rb");
    if (fp == NULL) {
        fprintf(stderr, "ERROR: cannot open test_out.raw.\n");
        return -1;
    }

    long int size;
    fseek(fp, 0L, SEEK_END);
    size = ftell(fp);
    if(size < 0) {
        fprintf(stderr, "ERROR: cannot calculate size of file.\n");
        return -1;
    }

    data = (unsigned char *)calloc(sizeof(unsigned char), size);
    if (data == NULL) {
        fprintf(stderr, "ERROR: cannot create data.\n");
        return -1;
    }

    if (!fread(data, sizeof(unsigned char), size, fp)) {
        fprintf(stderr, "ERROR: could not read data into buffer.\n");
        return -1;
    }

    int i;
    for (i = 0 ; i < size; ++i) {
        if (i && (i%10) == 0) putchar('\n');
        fprintf(stdout, " --%c-- ", (unsigned char)(data[i]));
    }

    free(data);
    fclose(fp);
    return 0;
}
like image 990
Matthew Hoggan Avatar asked May 29 '26 00:05

Matthew Hoggan


1 Answers

You moved to the end of the file with fseek, and then you're trying to read from it - but, since you are already at the end of the file, the read fails because there's nothing left to read.

Before attempting the read, get back to the beginning of file with another fseek:

fseek(fp, 0L, SEEK_SET);

or, even simpler, with a rewind:

rewind(fp);
like image 161
Matteo Italia Avatar answered May 31 '26 13:05

Matteo Italia