Sergey Ryabov Sergey Ryabov - 25 days ago 5
C Question

How to fwrite to pointer of pointer?

I have a function which should store content of a

to pointer of pointer -
. When I am trying to check the result of
function - it returns nothing to
. What am I doing wrong here? Did I allocate memory correctly (if I want to copy the whole file)?

bool load(FILE* file, BYTE** content, size_t* length)
int len = 0, writn = 0;

fseek(file, 0, SEEK_END);
*length = len = ftell(file);

*content = (char) malloc((len + 1) * sizeof(char)); //(len + 1) * sizeof(char)

writn = fwrite(*content, len + 1, 1, file);

return true;


You probably opened the file for reading "r" mode and fwrite() will write into the file, not read. If this is the case fwrite() will fail of course.

Perhaps you simply need

// Use long int for `length' to avoid a problem with `ftell()'
// read the documentation
bool load(FILE* file, BYTE **content, long int *length)
    fseek(file, 0, SEEK_END);
    *length = ftell(file);
    if (*length == -1)
        return false;    
    *content = malloc(*length + 1);
    if (*content == NULL)
        return false;
    if (fread(*content, 1, *length, file) != *length) {
        *content = NULL;
        return false;
    (*content)[*length] = '\0';
    return true;

You also, try to "read" more data than available, since you get the file length and still try to read 1 more byte.