fread return value 1 byte, even though file is getting read completely
c, file-io
Solution
Try this:
//byteCount = fread(filecontents, filesize, 1, fh);
byteCount = fread(filecontents, 1, filesize, fh);
Problem
I'm reading in a tarfile like this: ``` fh = fopen(filename, "r"); if (fh == NULL) { printf("Unable to open %s.\n", filename); printf("Exiting.\n"); return 1; } fseek(fh, 0L, SEEK_END); filesize = ftell(fh); fseek(fh, 0L, SEEK_SET); filecontents = (char*)malloc(filesize + 1); // +1 for null terminator byteCount = fread(filecontents, filesize, 1, fh); filecontents[filesize] = 0; fclose(fh); if (byteCount != filesize) { printf("Error reading %s.\n", filename); printf("Expected filesize: %ld bytes.\n", filesize); printf("Bytes read: %d bytes.\n", byteCount); } ``` I then proceed to decode the contents of the tarfile and extract the files stored within. Everything works correctly, and the files get extracted just fine, yet `fread()` is returning `1` instead of `filesize`. The output I get is: ``` Error reading readme.tar. Expected filesize: 10240 bytes. Bytes read: 1 bytes. ``` According to CPP Reference on `fread`, the return value should be the number of bytes read.