Leia linha por linha a partir de um buffer de soquete

Eu quero escrever uma função que leia linha por linha a partir de um buffer de soquete obtido do terceiro parâmetro deread() função deunistd.h cabeçalho.

Eu escrevi isso:

int sgetline(int fd, char ** out)
{
    int buf_size = 128;
    int bytesloaded = 0;
    char buf[2];
    char * buffer = malloc(buf_size);
    char * newbuf;
    int size = 0;

    assert(NULL != buffer);

    while( read(fd, buf, 1) > 0 )
    {
        strcat(buffer, buf);
        buf[1] = '\0';
        bytesloaded += strlen(buf);
        size = size + buf_size;

        if(buf[0] == '\n')
        {
            *out = buffer; 
            return bytesloaded;
        }

        if(bytesloaded >= size)
        {
            size = size + buf_size;
            newbuf = realloc(buffer, size);

            if(NULL != newbuf)
            {
                buffer = newbuf;
            }
            else 
            {
                printf("sgetline() allocation failed!\n");
                exit(1);
            }
        }
    }

    *out = buffer;
    return bytesloaded;
}

mas tenho alguns problemas com esta função, por exemplo, se a entrada for algo como:

HTTP/1.1 301 Moved Permanently\r\n
Cache-Control:no-cache\r\n
Content-Length:0\r\n
Location\r\nhttp://bing.com/\r\n
\r\n\r\n

e eu faç

int sockfd = socket( ... );
//....
char* tbuf;
while(sgetline(sockfd, &tbuf) > 0)
{
    if(strcmp(tbuf,"\r\n\r\n") == 0)
    {
       printf("End of Headers detected.\n");
    }
}

o aplicativo C acima não gera"End of Header detected.". Por que isso e como posso corrigir isso?

questionAnswers(6)

yourAnswerToTheQuestion