Sergey Ryabov Sergey Ryabov - 2 months ago 17
C Question

How to fwrite to pointer of pointer?

I have a function which should store content of a

file
to pointer of pointer -
content
. When I am trying to check the result of
fwrite
function - it returns nothing to
writn
. 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);
rewind(file);

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

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

return true;
}

Answer

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);
    rewind(file);
    if (*length == -1)
        return false;    
    *content = malloc(*length + 1);
    if (*content == NULL)
        return false;
    if (fread(*content, 1, *length, file) != *length) {
        free(*content);
        *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.

Comments