那么,我需要帮助:我想写一个函数,从一个套接字缓冲区中逐行读取,从read()
函数的第三个参数中获取第unistd.h
表头。从套接字缓冲区逐行读取
我已经写了这个:
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;
}
但我有一些问题,与此功能,例如,如果输入的是一样的东西:
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
和我做
int sockfd = socket(...);
//....
char* tbuf;
while(sgetline(sockfd, &tbuf) > 0)
{
if(strcmp(tbuf,"\r\n\r\n") == 0)
{
printf("End of Headers detected.\n");
}
}
上面的C应用程序不输出"End of Header detected."
。为什么?如何解决这个问题?非常感谢提高这个功能的提示。提前致谢。 :)
怎样才能得到**值得注意的问题徽章** ** upvotes哈哈。 – Jack 2013-05-08 00:52:58
请参阅[TLPI的readline](http://man7.org/tlpi/code/online/dist/sockets/read_line.c.html)实现。 – mmoya 2013-09-28 16:02:28