C Program Loads a File Into Memory Dynamically allocated on heap and Stores address thereof in *content and length thereof in *length.

How to write a C Program to Loads a file into memory dynamically allocated on heap and Stores address thereof in *content and length thereof in *length in C Programming Language.


Solution -

/**
 * Loads a file into memory dynamically allocated on heap.
 * Stores address thereof in *content and length thereof in *length.
 */
bool load(FILE* file, BYTE** content, size_t* length)
{
    int index = 0;
    BYTE* buffer = malloc(1);
    int status = fread(buffer+index, 1, 1, file);
 
    while(status){
        index++;
        printf("About to ralloc %i\n", index);
        buffer = realloc(buffer, index);
        printf("Yay!\n");
        if(buffer != NULL){
            status = fread(buffer+index, 1, 1, file);
        }
        else{
            *length = 0;
            *content = NULL;
            return false;
        }
    }
    *content = buffer;
    *length = index;
    return true;
}


Learn More :