用libcurl写一个文件下载的代码
时间: 2023-03-08 17:57:26 浏览: 75
我可以为你提供一个使用libcurl写一个文件下载的代码的例子:#include <stdio.h>
#include <curl/curl.h>int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/example.zip");
/* 设置文件保存到本地 */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
/* 执行下载 */
res = curl_easy_perform(curl);
/* 检查错误 */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
/* 释放资源 */
curl_easy_cleanup(curl);
}
return 0;
}
相关问题
利用C++写一个下载文件的代码放到线程里
好的,以下是一个简单的利用C语言写的下载文件的代码,可以放到线程中运行:
```c
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
void download_file(char *url, char *filename) {
CURL *curl;
FILE *fp;
CURLcode res;
curl = curl_easy_init();
if (curl) {
fp = fopen(filename, "wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
}
curl_easy_cleanup(curl);
fclose(fp);
}
}
int main() {
char *url = "http://example.com/file.zip";
char *filename = "file.zip";
download_file(url, filename);
return 0;
}
```
这个代码使用了libcurl库来进行文件下载,可以通过设置CURLOPT_URL选项来指定要下载的文件的URL,通过设置CURLOPT_WRITEDATA选项来指定要将文件内容写入的文件指针。在下载完成后,需要调用curl_easy_cleanup函数来释放资源,并关闭文件指针。
libcurl下载文件实例
好的,以下是一个使用libcurl下载文件的示例代码:
```c++
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
FILE *fp;
CURLcode res;
char *url = "https://www.example.com/file.txt";
char outfilename[FILENAME_MAX] = "file.txt";
curl = curl_easy_init();
if(curl) {
fp = fopen(outfilename,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
}
curl_easy_cleanup(curl);
fclose(fp);
}
return 0;
}
```
这个示例中,我们首先初始化了一个CURL对象,然后设置了要下载的URL和要保存的文件路径。接着我们打开了一个文件指针,用于将下载的数据写入到文件中。然后我们通过curl_easy_setopt()函数设置了数据的写入方式,这里我们使用了默认的写入函数,将数据写入到指定的文件中。最后我们执行了一个HTTP GET请求,并将下载的数据写入到文件中。如果请求成功,curl_easy_perform()函数会返回CURLE_OK,否则会返回一个错误码。最后我们清理并释放了CURL对象,并关闭了文件指针。