Search code examples
ctcpwebserver

Read binary file chunk by chunk into memory buffer in C


I have to read a binary file in my webserver and send it to client via TCP. I decided to read it by chunks. How can I do it?

My code with fgets works only with text files (code, that checks return values is omitted):

char buf[2048];

fgets(buf, sizeof(buf), fp);
while (!feof(fp))
{
    Server_TCP_Send(socket, buf, strlen(buf));
    fgets(buf, sizeof(buf), fp);
}
fclose(fp);

Solution

  • Use fread() instead of fgets(), and pay attention to the return value:

    char buf[2048];
    size_t buflen; 
    
    while (1) {
        buflen = fread(buf, 1, sizeof(buf), fp);
        if (buflen < 1) {
            if (!feof(fp)) {
                // a read error occured...
            }
            break;
        }
        Server_TCP_Send(socket, buf, buflen);
    }
    fclose(fp);
    

    Alternatively, some platforms have functions for sending files over a socket. For example, sendfile() on Linux, or TransmitFile() on Windows.