前言
说实话,就这种东西我居然搞了快两个小时,一开始没有搞懂curl函数中设置的回调函数用法以及将参数传入回调函数的意义,经过我查阅官网并融合官网与某些网络知识,写出这个可以在下载时显示下载百分比的代码(其实主要是网络实例不多,其实一旦看过实例,理解起来就很容易)
相关知识
下载文件的关键语句:
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, FetchFiles);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile);
这两句设定了下载文件的操作,FetchFiles为回调函数,该回调函数决定了CURLOPT_WRITEFUNCTION该做什么操作,
&ftpfile为回调函数的第四个参数,为回调函数运行提供完整参数
这两步是固定的操作,包括回调函数的参数数量,类型都是定死的,不可以随意修改
curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, my_progress_func);
curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, progress_data);
这两句是在文件下载时获取文件大小及实时下载的大小,my_progress_func为回调函数,该函数为固定格式,所有想对实时文件读取有关的操作都可以写在这里面,包括将实时信息展示在进度条上等
progress_data为回调函数的参数之一,可以设置任意你需要的参数
代码
#include <string>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include "curl.h"
#include <stdio.h>
using namespace std;
#pragma comment(lib,"libcurl.lib")
struct FtpFile
{
const char *filename;
FILE *stream;
};
static size_t FetchFiles(void *buffer, size_t size, size_t nmemb, void *stream)
{
struct FtpFile *out = (struct FtpFile *)stream;
if (out && !out->stream)
{
// open file for writing
out->stream = fopen(out->filename, "wb");
if (!out->stream)
return -1; // failure, can't open file to write
}
return fwrite(buffer, size, nmemb, out->stream);
}
int my_progress_func(char *progress_data,
double t, /* dltotal */
double d, /* dlnow */
double ultotal,
double ulnow)
{
printf("%s %g / %g (%g %%)\n", progress_data, d, t, d*100.0/t);
return 0;
}
int DownloadFtpFile()
{
CURL *curl;
CURLcode res;
char *progress_data = "* ";
struct FtpFile ftpfile = {
"E:\\vs文档\\1031CURL_TEST\\FtpDownLoad\\UltraEdit-32.rar", // name to store the file as if succesful//
NULL
};
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL,"ftp://ljl:[email protected]:21/UltraEdit-32(UE)/UltraEdit-32.rar");
curl_easy_setopt(curl, CURLOPT_USERPWD, "ljl:521125");
// Define our callback to get called when there's data to be written //
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, FetchFiles);
// Set a pointer to our struct to pass to the callback //
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, FALSE);
curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, my_progress_func);
curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, progress_data);
// Switch on full protocol/debug output //
//curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
res = curl_easy_perform(curl);
// always cleanup
curl_easy_cleanup(curl);
if (CURLE_OK != res)
{
//we failed
fprintf(stderr, "curl told us %d\n", res);
}
}
if (ftpfile.stream)
fclose(ftpfile.stream); // close the local file
curl_global_cleanup();
getchar();
return 0;
}
int main(void)
{
DownloadFtpFile();
return 0;
}
后续
有些代码中的知识上面已经说过了,这里说下运用libcurl的重点:curl_easy_setopt
curl_easy_setopt是全过程中最重要的一环,该函数可以多次调用以完成你的多个目标,而该函数的回调函数更是重中之重!!!
下面给出curl_easy_setopt的解读链接
https://blog.csdn.net/qq_37059136/article/details/83820529
运行结果
显示下载百分比回调函数完全可以做更多的事,这完全取决于你的目的