原理是用的C/C++的 URLDownloadToFile函数所有的参数都必须是LPCWSTR,所以第一个结构体是string转LPCWSTR
第二个结构体才是真正的下载文件的代码,主函数只需要传入两个string参数,一个是下载链接,一个是保存路径
#include <stdio.h>
#include <tchar.h>
#include <string>
#include <string.h>
#include <iostream>
#include <windows.h>
#include <Urlmon.h>
using namespace std;
#pragma comment(lib,"Urlmon.lib") //加入链接库
LPCWSTR stringToLPCWSTR(std::string orig)
{
size_t origsize = orig.length() + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
wchar_t *wcstring = (wchar_t *)malloc(sizeof(wchar_t)*(orig.length() - 1));
mbstowcs_s(&convertedChars, wcstring, origsize, orig.c_str(), _TRUNCATE);
return wcstring;
}
void download( string dourl ,string a)
{
LPCWSTR url = stringToLPCWSTR(dourl);
printf("下载链接: %S\n", url);
TCHAR path[MAX_PATH];
GetCurrentDirectory(MAX_PATH, path);
LPCWSTR savepath = stringToLPCWSTR(a);
wsprintf(path, savepath, path);
printf("保存路径: %S\n", path);
HRESULT res = URLDownloadToFile(NULL, url, path, 0, NULL);
if (res == S_OK)
{
printf("下载完毕\n");
}
else if (res == E_OUTOFMEMORY)
{
printf("接收长度无效,或者并未定义\n");
}
else if (res == INET_E_DOWNLOAD_FAILURE)
{
printf("URL无效\n");
}
else
{
printf("未知错误\n", res);
}
}
int main()
{
string downurl = "http://www.anyuer.club";
string savepath = "D://abc.index";
download(downurl , savepath );
while (1);
return 0;
}
效果截图

发表评论: