Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fread return value 1 byte, even though file is getting read completely

Tags:

c

file-io

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.

like image 854
xbonez Avatar asked Dec 15 '22 13:12

xbonez


1 Answers

Try this:

//byteCount = fread(filecontents, filesize, 1, fh);
byteCount = fread(filecontents, 1, filesize, fh);
like image 58
Leo Chapiro Avatar answered Jan 18 '23 23:01

Leo Chapiro