[英]How to Strip the header from data received using recv in c++?
I have made this code below to download large file and save it to file.我在下面制作了这段代码来下载大文件并将其保存到文件中。 (I removed not important parts) (我删除了不重要的部分)
int nDataLength;
int i = 0;
static char buffer[4096];
while ((nDataLength = recv(Socket, buffer, sizeof(buffer), NULL)) > 0)
{
//MessageBoxA(0, std::to_string(nDataLength).c_str(), "TEST", 0);
fwrite(buffer, nDataLength, 1, pFile);
}
Now It saves file, but it also saves HTTP header.现在它保存文件,但它也保存 HTTP 标头。 Now I don't really know how to strip the header from received data.现在我真的不知道如何从接收到的数据中去除标题。
If it was small enough I could read Content-Length from buffer and then open the file again and remove header, but thats not the option cause buffer will be overwritten with new data.如果它足够小,我可以从缓冲区读取内容长度,然后再次打开文件并删除标题,但这不是选项,因为缓冲区将被新数据覆盖。
Also I cannot use other libraries like libcurl etc.我也不能使用其他库,如 libcurl 等。
EDIT:编辑:
char* content = strstr(buffer, "\r\n\r\n");
if (content != NULL) {
content += 4;
fwrite(content, nDataLength, 1, pFile);
}
else
{
fwrite(buffer, nDataLength, 1, pFile);
}
OK, I came up with function that strips header before saving.好的,我想出了在保存之前去除标题的功能。
int nDataLength;
int i = 0;
static char buffer[4096];
while ((nDataLength = recv(Socket, buffer, sizeof(buffer), NULL)) > 0)
{
char* content = strstr(buffer, "\r\n\r\n");
if (content != NULL) {
std::string s2(buffer);
size_t p = s2.find("\r\n\r\n");
fwrite(buffer+p+4, nDataLength-p-4, 1, pFile);
}
else
{
fwrite(buffer, nDataLength, 1, pFile);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.