Search code examples
c++arraysbufferbytememcpy

Copy a specific part of a BYTE buffer to a structure+


I was working in my file loader, and i decided it was better for the next updates instead of keep using fread and fseek read the hole file to a BYTE buffer, and so did i, now i was wondering if theres no easy way of assigning part of this BYTE buffer to an structure.

I Already tried making a temp buffer with the same size as the structure, copy all the BYTE i need from the original buffer to it, and use memcpy, but it didn't work right, i just received a lot of random numbers (which i think i am receiving their pointers, but i don't know right).

Thank you for your time!

Edit: REAL Code

void memread(BYTE from[],int pos, void * to,size_t size) 
{   
    BYTE * temp = new BYTE[sizeof(BYTE)*size];

    for (unsigned int i = 0; i< 1+size; i++)
        temp[i] = from[i+pos];

    memcpy(to,temp,size);

}


... inside the file loader ...


fseek(fl,0,SEEK_END);
const int memory_size = (int)ftell(fl);


BYTE * memory = new BYTE[sizeof(BYTE)*memory_size];
fseek(fl,0,SEEK_SET);

for (int i=1;i<=memory_size;i++)
fread(&memory[i],sizeof(BYTE),1,fl);

fclose(fl);

int memory_pos = 0;

XM::Memory xm;
memset(&xm,0,sizeof(XM::Memory));


memread(memory,1,&xm.Header,sizeof(XM::Header));

Solution

  • First you are reading the file byte by byte, which will give you a bad performance. Next, your memread (where you don't free the temp buffer!) can be replaced by a simple memcpy

    fseek(fl, 0, SEEK_END); 
    const int memory_size = (int)ftell(fl); 
    
    BYTE* memory = new BYTE[sizeof(BYTE) * memory_size];
    fseek(fl, 0, SEEK_SET); 
    
    fread(memory, sizeof(BYTE), memory_size, fl); 
    
    fclose(fl); 
    
    int memory_pos = 0; 
    
    XM::Memory xm;
    memset(&xm, 0, sizeof(XM::Memory)); 
    
    memcpy(&xm.Header, memory + memory_pos, sizeof(XM::Header);
    

    Never forget to delete[] your allocated arrays like temp and memory