libcurl控制台进度条,用于文件下载

在这里,我实现了从服务器下载文件的代码。 它的工作正常。 现在我想制作我自己的进度条function,它可以计算一些数据,如剩余的秒数据速率等等。所以从这里我发现了一种使用curl进度条选项的方法。 我们如何启用此选项。 我完全做到了这一点。

我把我的代码放在下面。 在此代码中, my_progress_func根据curl库时间间隔频繁调用。 我想更改此间隔时间并使其为1秒。 是否有可能在curl库中使用为curl库设置一些选项?

我希望每1秒后调用一次my_progress_func函数。

代码:

 #include  #include  long test =0; struct FtpFile { const char *filename; FILE *stream; long iAppend; }; static size_t my_fwrite(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, out->iAppend ? "ab":"wb"); if(!out->stream) return -1; /* failure, can't open file to write */ } out->iAppend += nmemb; return fwrite(buffer, size, nmemb, out->stream); } int my_progress_func(void *bar, double t, /* dltotal */ double d, /* dlnow */ double ultotal, double ulnow) { printf("%f : %f \n", d, t); return 0; } int main(void) { CURL *curl; CURLcode res; int c; struct FtpFile ftpfile={ "dev.zip", /* 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, "sftp://root:xyz_@192.170.10.1/mnt/xyz.tar"); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 120L); /* Define our callback to get called when there's data to be written */ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite); /* Set a pointer to our struct to pass to the callback */ curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile); curl_easy_setopt(curl, CURLOPT_FTPPORT, "-"); /* Switch on full protocol/debug output */ curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, my_progress_func); res = curl_easy_perform(curl); printf("res is %d\n, data get %ld\n", res, ftpfile.iAppend); ///Retry upto 100 times it timeout or connection drop occur for (c = 0; (res != CURLE_OK) && (c < 100); c++) { curl_easy_setopt(curl, CURLOPT_RESUME_FROM , ftpfile.iAppend); res = curl_easy_perform(curl); if(res == CURLE_OK) c =0; printf("%d res is %d\n, data get %ld\n",c, res, ftpfile.iAppend); } /* always cleanup */ curl_easy_cleanup(curl); } if(ftpfile.stream) fclose(ftpfile.stream); /* close the local file */ curl_global_cleanup(); return 0; } 

根据curl文档: http : //curl.haxx.se/libcurl/c/curl_easy_setopt.html

应该与找到的curl_progress_callback原型匹配的函数指针。 无论数据是否被传输,此函数都会被libcurl而不是其内部等效函数调用, 在操作期间(大约每秒一次或更早)经常间隔 。 传递给回调的未知/未使用的参数值将设置为零(如果您只下载数据,则上载大小将保持为0)。 从此回调返回非零值将导致libcurl中止传输并返回CURLE_ABORTED_BY_CALLBACK。

如果它的调用过于频繁,那么你可以使用time()和静态var来限制它,如下所示:

 static time_t prevtime; time_t currtime; double dif; static int first = 1; if(first) { time(&prevtime); first = 0; } time(&currtime); dif = difftime(currtime, prevtime); if(dif < 1.0) return; prevtime = currtime; 

显然,你冒着curl可能再次无法再调用此函数的风险。