frbry
frbry

Reputation: 365

Sending Files With Sockets

I'm trying to create a basic HTTP server to learn more about how it works. I'm having difficulties with sending binary files to the client. My code is as below:

char * buffer = (char *)malloc(sizeof(char) * 512);
fseek(content_file, 0, SEEK_SET);
while (!feof(content_file)) {
    size_t read = fread(buffer, sizeof(char), sizeof(buffer), content_file);
    if (read > 0) {
        client->send((const void *)buffer);
    }
}
fclose(content_file);
free(buffer);

Now I know it can send some unnecessary data after the last block read but before trying to fix it, I want to know what's wrong with it. It was working fine for text files and I was using fgets. But after switching to fread to support binary files, text files are corrupted and became something like this: ThisÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ ("This" is the only correct part in the sent data)

Obviously I'm missing something but can you please help me to do this correctly?

Edit:

Using a buffer_size value instead of sizeof(buffer) fixed the missing/corrupted data problem.

Upvotes: 1

Views: 407

Answers (1)

Bo Persson
Bo Persson

Reputation: 92271

You problem is that sizeof(buffer) gives you the size of the pointer, not what it points to.

Add a buffer_size and use that both for malloc and freed.

Upvotes: 4

Related Questions