Search code examples
cpointersarraysfwrite

Writing ByteArray to file in c


I have a struct which holds some ByteArray data

typedef struct {
    uint32_t length;
    uint8_t* bytes;
} FREByteArray;  

And here I am trying to save this to a file

FREByteArray byteArray;

if((fileToWrite = fopen(filePath, "wb+")) != NULL){
    fwrite(&byteArray.bytes, 1, byteArray.length, fileToWrite);
    fclose(fileToWrite);
}

But this doesn't seem to be saving all of the data, the saved file size is 16KB, actual data is about 32KB. I think fwrite is not able to write the whole bytearray to the file.

Is this the correct way to save the ByteArray? Is there a limit how much fwrite can handle in a single call?


Solution

  • Replace

    fwrite(&byteArray.bytes, 1, byteArray.length, fileToWrite);
    

    with

    fwrite(byteArray.bytes, 1, byteArray.length, fileToWrite);
    

    And as pointed out by @Sourav Ghosh make sure that byteArray.bytes is pointing to the correct source location.