用curl实现的简单的下载程序——附超详细注释,实操无问题

之前捣鼓了一番在电脑上安装好了最先的curl库,今天迫不及待的用了一波,实操感觉不错!下面看demon
安装过程:curl下载安装教程
一、程序demon:

#include <curl/curl.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

char DOWNLOAD_PATH[300];

int download_function(char *url, char *down_path)
{
	if ((NULL == url) || (NULL == down_path)) {
		printf("param_error");
		return -1;
	}
	CURL *curl = curl_easy_init();//创建一个简单的句柄,操作完必须调用curl_easy_cleanup();函数
	if (NULL == curl) {
		printf("curl_easy_init error");
		return -1;
	}

	FILE *file = fopen(down_path, "wb");
	int errnum = 0;
	if (NULL == file) {
		errnum = errno;
		printf("open fail errno=%d,reason=%s", errnum,
		       strerror(errnum));
		return -1;
	}

	curl_easy_setopt(curl, CURLOPT_WRITEDATA, file);//下载路径
	curl_easy_setopt(curl, CURLOPT_URL, url);//下载地址,要访问的网址链接
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);//使用毫秒超时 需要关闭这个signal功能,curl_setopt($ch, CURLOPT_NOSIGNAL, true);
	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT,10);//连接超时10s
	curl_easy_setopt(curl, CURLOPT_TIMEOUT,30);//下载响应超时30s,30s没下载完退出 
	curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);//调试信息打开


	CURLcode res = curl_easy_perform(curl);//以阻塞方式执行整个请求
	if (CURLE_OK != res) {
		fclose(file);
		curl_easy_cleanup(curl);//结束一个curl_easy_init()创建的简易句柄
		printf("curl_easy_perform failed:%s\n",
		       curl_easy_strerror(res));//解析curl请求发生错误时返回的错误编码的含义
		return -1;
	}

	fclose(file);
	curl_easy_cleanup(curl);//结束一个curl_easy_init()创建的简易句柄
	return 0;
}

int main()
{
	int ret;
	char url[300];
	printf("please url path:\n");
	scanf("%s",url);
	printf("path = %s\n",url);
	printf("pleas install_path:\n");
	scanf("%s",DOWNLOAD_PATH);
	ret = download_function(url,DOWNLOAD_PATH);
	printf("ret = %d\n",ret);
	return 0;
}



二、运行演示
1.在网上可以百度一个下载链接,然后复制过来,去下载,这里小编去百度了有道词典进行演示,平时用有道比较方便,哈哈,顺便推荐一波
在这里插入图片描述
2.运行演示
在这里插入图片描述
欢迎留言交流技术,小编也是一只待飞的菜鸟

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值