1

So far, my server seems to be working correctly except when it comes to the step of loading a file into memory. I'm using fread to get the info. from file, and my goal is to store the number of bytes successfully read in the variable bytes, but fread seems to be returning 0 every time. However (based on what I've found using gdb), fread otherwise seems to have worked correctly (the buffer stores the first 512 bytes of file). I just can't figure out why fread returns 0 when it otherwise seems to be working--this throws off the entire rest of the load function code. Here it is below:

    bool load(FILE* file, BYTE** content, size_t* length)
{

//ensure file is open
if(file == NULL)
{
    return false;
}

//initialize content and length
*content = NULL;
*length = 0;

while(true)
{
    char* buffer = malloc(BYTES);
    int bytes = fread(buffer, BYTES, 1, file);
    if(bytes != BYTES)
    {
        *content = realloc(*content, *length + bytes);
        if(*content == NULL)
        {
            *length = 0;
            return false;
        }

        memcpy(*content + *length, buffer, bytes);
        *length += bytes;

        return true;
    }

    *content = realloc(*content, *length + bytes);
    if(*content == NULL)
    {
        *length = 0;
        return false;
    }

    memcpy(*content + *length, buffer, bytes);
    *length += bytes;

}

return false;
}
1
  • Where do you assign the value for BYTES? If it is a global variable, how do you define it? It doesn't look like it has a value and you use it for malloc when defining buffer. – Brendan Rafferty May 28 '16 at 16:57
1

From man fread (emphasis added):

On success, fread() and fwrite() return the number of items read or written. This number equals the number of bytes transferred only when size is 1. If an error occurs, or the end of the file is reached, the return value is a short item count (or zero).

fread signature is size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);. Check your call to fread.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .