C++ 下载直连文件 函数封装成功

原理是用的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;
}

 下面附赠运行截图,

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值