我遇到以下代码的问题。我已经看到大量使用InternetReadFile保存到文件的示例。但我找不到一个,或让它为char []工作。我想添加szBuffer以获取holdBuff,然后将内容设置为holdBuff。
#include <stdio.h>
#include <tchar.h>
#include <string.h>
#include <windows.h>
#include <WinInet.h>
HINTERNET hSession;
void urlToChar(char* url, char** content);
int main()
{
hSession = InternetOpen("Mozilla/4.0 (compatible) Poison", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
char* content;
urlToChar("http://google.com/", &content);
printf("%s",content);
return 0;
}
void urlToChar(char* url, char** content)
{
HINTERNET hConnect = InternetConnect(hSession, _T(""),INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
HINTERNET hRequest = InternetOpenUrl(hSession, url, NULL, 0, 0, 0);
if (hRequest)
{
char holdBuff[] = "";
char szBuff[1025];
memset(szBuff, 0x00, sizeof(szBuff));
DWORD bytesRead;
while (InternetReadFile(hRequest, szBuff, 1024, &bytesRead) == TRUE && bytesRead > 0)
{
// Cat szBuff to holdBuff
memset(szBuff, 0x00, sizeof(szBuff));
}
*content = holdBuff;
// memset(holdBuff, 0x00, sizeof(holdBuff)); <-- Need this?
}
InternetCloseHandle(hRequest);
InternetCloseHandle(hConnect);
}
答案 0 :(得分:2)
变量声明
char xyz[] = "Hello World!";
将告诉编译器将字符串的内容放在堆栈上。当然,当你的函数返回时,堆栈会消失。
所以在你的情况下:
char holdBuff[] = "";
...
*content = holdBuff;
这告诉编译器创建一个长度为1的字符串(NULL终止符)作为局部变量。仅仅因为您将content
的值设置为holdBuff
并不意味着holdBuff
指向的内容不再存在。
你必须纠正两件事。首先,您必须使用strcpy()
或类似功能。其次,您必须为holdBuff
分配足够的空间。
示例:
char holdBuff[4096]; // or some other sufficiently large size
...
*content = malloc (strlen(holdBuff) + 1);
strcpy (*content, holdBuff);
完成后,您需要free(content)
main()
。
现在,关于如何实际连接:如果您忘记使用szBuff
并直接写入holdBuff
,您的表现会好得多。
char* temp = holdBuff;
while (InternetReadFile(hRequest, temp, 1024, &bytesRead) == TRUE && bytesRead > 0)
{
temp += bytesRead;
}
*temp = '\0'; // manually append NULL terminator
现在holdBuff
将拥有您想要的数据而无需中间连接。
答案 1 :(得分:0)
void urlToChar(char* url, char** content)
{
HINTERNET hConnect = InternetConnect(hSession, _T(""),INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
HINTERNET hRequest = InternetOpenUrl(hSession, url, NULL, 0, 0, 0);
if (hRequest)
{
char holdBuff[] = ""; //do not use fixed size char array and allocate buffer in stack,you can allocate large enough buffer in heap,but recommend you can use string or CString
char szBuff[1025];
memset(szBuff, 0x00, sizeof(szBuff));
DWORD bytesRead;
while (InternetReadFile(hRequest, szBuff, 1024, &bytesRead) == TRUE && bytesRead > 0)
{
// Cat szBuff to holdBuff
//strcat when using char array
// operator+ when using stl string
// [stl string][1]
memset(szBuff, 0x00, sizeof(szBuff));
}
*content = holdBuff;
// memset(holdBuff, 0x00, sizeof(holdBuff)); <-- Need this?
}
InternetCloseHandle(hRequest);
InternetCloseHandle(hConnect);
}