char*+text获取函数格式
如果你需要即获取一段内存, 也保存到文本. 这种格式比较整洁: 以下是一个sock例子。
转载请注明出处.
char *content = (char *)malloc(50000);
int cttLen = 50000;
GetPage(get, host, des, &content, cttLen);
free(content);
content = NULL;
int GetPage(char *get, char *host, char *des, char **content, int &cttLen)
{
//下载buff + 内嵌文件存储
//拼头
char head_static[512] = " HTTP/1.1\r\n"
"Accept: */*\r\n"
"Accept-Encoding: gzip, deflate\r\n"
"Accept-Language: zh-cn\r\n"
"Connection: Keep-Alive\r\n"
"HOST: ";
strcat_s(head_static, host);
strcat_s(head_static, "\r\n");
strcat_s(head_static, "User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; QQDownload 677; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E)\r\n\r\n");
char head[1024];
memset(head, 0, 1024);
strcat_s(head, "GET ");
strcat_s(head, get);
strcat_s(head, head_static);
printf("%s\n", head);
//下载
int count;
count = InitSock2(host, head, content, cttLen);
//存入文件
if (count != -1)
{
FILE *f;
f = fopen(des, "wb");
fwrite(*content, 1, count, f);
fclose(f);
return 1;
}
else
return -1;
}
int InitSock2(const char *host, const char *header, char **contentBuf, int &bufLen)
{ //contentBuf 由外部申请, 如果空间小了重新申请.
//需要处理 1. 返回错误网页识别, 重新下载 2.返回内容不全, 重新下载 3.如果下载3次不成功, 返回错误
//开启
WSADATA WSAData={0};
if(WSAStartup(MAKEWORD(2,2), &WSAData))
return -1;
//建sock
SOCKET sock;
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
//获取主机地址
struct hostent *pURL;
pURL = gethostbyname(host);
//设置地址
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = *((unsigned long*)pURL->h_addr);
addr.sin_port = htons(80);
//链接, 发送
connect(sock, (SOCKADDR *)&addr, sizeof(addr));
send(sock, header, strlen(header), 0);
//接收
int irev(0), sumRev(0), allRev(0), normal(1);
char headBuf[MBUFSIZ], buf[128];
char *pContent, *pLength, *pEnd;
irev = recv(sock, headBuf, MBUFSIZ, 0);
printf("%s\n", headBuf);
//读接收长度
pLength = strstr(headBuf, "Content-Length");
if(pLength != NULL)
{
pEnd = strstr(pLength, "\r\n");
pLength = FindFirstNum(pLength);
pEnd = FindFirstUnNum(pLength);
memset(buf, 0, 128);
memcpy(buf, pLength, pEnd - pLength);
allRev = atoi(buf);
}
else
{
pEnd = headBuf;
allRev = 50000;
normal = 0;
}
char *contentHead;
int len;
if (bufLen < allRev)
{
*contentBuf = contentHead = (char *)realloc(*contentBuf, allRev+1);
bufLen = allRev;
}
else
*contentBuf = contentHead;
//读内容
pContent = strstr(pEnd, "\r\n\r\n");
len = irev-(pContent-headBuf+4);
memcpy(*contentBuf, pContent+4, len);
*contentBuf += len;
sumRev += len;
while ( (irev= recv(sock, *contentBuf, MBUFSIZ, 0)) > 0)
{
*contentBuf += irev;
sumRev += irev;
if(sumRev == allRev)break;
}
**contentBuf = '\0';
//关闭
closesocket(sock);
WSACleanup();
*contentBuf = contentHead;
if(sumRev == allRev || normal == 0)
return sumRev;
else
return -1;
}