那麼,我需要幫助:我想寫一個函數,從一個套接字緩衝區中逐行讀取,從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