Get data from a Internet file into a char

Pages: 12
@modoran: Interesting. I have never tried to stuff binary data into a std::string or std::wstring. Never even occurred the idea. If I have time, I'll try it out.
Anyway, this is what my function looks like now

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
char* DownloadBytes(char* szUrl) {
	HINTERNET hOpen = NULL;
	HINTERNET hFile = NULL;
	vector<char> tempdata;
	char* data = NULL;
	DWORD dwBytesRead = 0;

	hOpen = InternetOpen("MyAgent", NULL, NULL, NULL, NULL);
	if(!hOpen) return data;

	hFile = InternetOpenUrl(hOpen, szUrl, NULL, NULL, INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE, NULL);
	if(!hFile) {
		InternetCloseHandle(hOpen);
		return data;
	}
	do {
		char buffer[1023];
		InternetReadFile(hFile, (LPVOID)buffer, _countof(buffer), &dwBytesRead);
		for (unsigned int i=0; i<dwBytesRead; i++) {
            tempdata.push_back(buffer[i]);
		}
	} while (dwBytesRead);

    data = new char[tempdata.size()];
	for (unsigned int i=0; i<tempdata.size(); i++) {
        data[i] = tempdata[i];
    }

    InternetCloseHandle(hFile);
    InternetCloseHandle(hOpen);

	return data;
}


but I am getting the same result. It's like one of those terror movies, when the killer is always after you, doesn't matter what you do. I feel like if I put this

1
2
3
char* DownloadBytes(char* szUrl) {
	return give_me_the_fu**ing_bytes;
}


I will get the same wrong result.

So, each group of dwBytesRead bytes is stored correctly into buffer. Now, whatever I do after that, the result is the same: only the first three bytes
O.K. After almost going insane with this, I realized that my function was right. The problem has been located in another function. Just when I was about to give up.

Thanks to everyone. Boys, raise the sails! We are continuing our journey to the Isle of the Great Programmer
Last edited on
@alexbnc,

Your function is dimmed wrong from the start. You only get a pointer to first character returned, but you NEED buffer size also returned somewhat, you can't use strlen or any C functions to do that when dealing with binary data.

My std::string approach is doing all this for you and works without issues, I used myself in few projects.

Of course, you can't use any functions that expects a null terminated string like printf.
I made what webJose said in one of his replies here. Instead of returning a char* the function returns a struct that contains the char array and its size, so I can have them.
Topic archived. No new replies allowed.
Pages: 12