I am looking for the most simple way to download a file in C++ (on Windows). URLDownloadToFile sounds great and does not require me to use curl or other fat libraries that I don't need - what are the requirements for this function? Which Windows's will it run on?
Thanks!
3 Answers
The documentation is there for a reason.
E: Just glancing at the documentation, it requires a minimum of Internet Explorer 3.0 and Windows 95. Vanishingly few computers do not meet those requirements.
E: Here's a sample of how to use this function. You also need to link Urlmon.lib to compile:
#include "stdafx.h"
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <Urlmon.h>
int _tmain(int argc, _TCHAR* argv[])
{ printf("URLDownloadToFile test function.\n"); TCHAR url[] = TEXT(""); printf("Url: %S\n", url); TCHAR path[MAX_PATH]; GetCurrentDirectory(MAX_PATH, path); wsprintf(path, TEXT("%s\\index.html"), path); printf("Path: %S\n", path); HRESULT res = URLDownloadToFile(NULL, url, path, 0, NULL); if(res == S_OK) { printf("Ok\n"); } else if(res == E_OUTOFMEMORY) { printf("Buffer length invalid, or insufficient memory\n"); } else if(res == INET_E_DOWNLOAD_FAILURE) { printf("URL is invalid\n"); } else { printf("Other error: %d\n", res); } return 0;
} 3 I use this function in a WTL C++ app and have yet to come across any PC that didn't support it (the app in question has been installed on thousands of clients, a mix of Windows 2000, XP, Vista and Windows 7). There are no .NET dependencies either BTW - it's buried in an old Internet Explorer Win32 DLL. It is very simple to use, accepts any URL and even a normal DOS-style filename will work (we sometimes use it to fetch files from a network share.)
1How exactly do you want this file downloaded, and from what source? If it is from your own source I can think of quite a few better ways, and more portable ways.
If you have the desire to download from your own source, simply set up a socket on either side, send the filesize, then send an array of chars from an fstream receive the array of characters and write to the destination fstream.
2