linux上使用curl下载指定url地址的文件,要有下载进度用百分比,用c语言
时间: 2024-09-25 22:05:28 浏览: 34
在Linux上使用C语言通过`libcurl`库来下载指定URL的文件,并显示下载进度(百分比),你可以按照以下步骤编写:
首先,你需要安装libcurl库。如果你使用的是Ubuntu或Debian,可以运行以下命令:
```bash
sudo apt-get install libcurl4-openssl-dev
```
然后,创建一个简单的C程序,例如`download.c`,添加以下内容:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
// 进度回调函数,用于更新下载进度
static size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata) {
int *progress = (int *)userdata;
*progress += size * nmemb;
double progress_percent = ((double)*progress / total_size) * 100;
printf("Downloaded %d bytes (%.2f%%)\r", *progress, progress_percent);
if (*progress == total_size) {
printf("\nDownload complete.\n");
return 0; // 停止回调
}
return size * nmemb; // 返回实际接收的数据量,告知libcurl继续读取
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <file_url>\n", argv[0]);
return 1;
}
CURL *curl;
CURLcode res;
long total_size;
int progress = 0;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (!curl) {
fprintf(stderr, "Error initializing libcurl\n");
return 1;
}
curl_easy_setopt(curl, CURLOPT_URL, argv[1]);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); // 设置回调函数
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &progress); // 将进度变量传递给回调
// 获取目标文件大小
res = curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD_TOT, &total_size);
if (res != CURLE_OK) {
fprintf(stderr, "Failed to get file size: %s\n", curl_easy_strerror(res));
curl_easy_cleanup(curl);
return 1;
}
printf("Starting download...\n");
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
fprintf(stderr, "Error downloading: %s\n", curl_easy_strerror(res));
} else {
printf("Download finished successfully.\n");
}
curl_easy_cleanup(curl);
curl_global_cleanup();
return res == CURLE_OK ? 0 : 1;
}
```
在终端中编译并运行这个程序:
```sh
gcc -o download download.c -lcurl
./download <file_url>
```
将 `<file_url>` 替换为你想要下载的文件的URL。
阅读全文