cbinaryfilessizeofftellijvm

wrong size of IJVM chunk file in c question


I am trying to implement an IJVM an read a binary file.

I understand that an .ijvm file contains a 32-bit magic number and any number of data blocks and that a data block has three parts. My intention is to first read and store the magic number which is always of constant size and then the data block to a different array. The .ijvm file looks like this:

1d ea df ad 00 01 00 00 00 00 00 00 00 00 00 00
00 00 00 07 10 30 10 31 60 fd ff

with the first 4 bytes (1d ea df ad) being the magic n. and the rest the data block.
After reading the file I determine the total size being 27 bytes, thus the rest should be 23 bytes.
However, no matter what I try, despite storing and reading correctly the magic and data parts, I always get a wrong data part size and not 23 bytes as I think it should.

byte_t bufferMagic[4];
byte_t *dataBlock;

FILE *fp;
uint32_t filelen;
uint32_t dataBlocklen;
fp = fopen(binary_file, "r");

fseek(fp, 0, SEEK_END); //compute the size of the file
filelen = ftell(fp);
fseek(fp, 0, SEEK_SET);
fprintf(stderr,"file:%s is %d bytes long\n",binary_file,filelen); //outputs27

//read magic number
fread(bufferMagic,1,4,fp);
fprintf(stderr, "Magic number: 0x%02hhx%02hhx%02hhx%02hhx \n",
    bufferMagic[0],bufferMagic[1],bufferMagic[2],bufferMagic[3]);

//read data block
dataBlock = (byte_t*)malloc(sizeof(byte_t) * filelen - 4);
//dataBlocklen = ftell(fp); //outputs 4
dataBlocklen = sizeof(dataBlock); //outputs 8
fread(dataBlock,1,filelen - 4,fp); //reads data block correctly

can you please explain what am I missing? Why both dataBlocklen not giving 23 bytes?


Solution

  • //dataBlocklen = ftell(fp); //outputs 4
    

    Returns 4 because current file offset is at 4th byte as you did fread for magicnumber prior to ftell.

    fread(bufferMagic,1,4,fp);
    

    and

    dataBlocklen = sizeof(dataBlock); //outputs 8
    

    Returns 8 because dataBlock is pointer, thus sizeof(pointer) is 8 byte on your machine.