开发者

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 usi开发者_如何学运维ng 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜