Linux 上使用libcurl下载http文件。
需要安装libcur
apt-get install libcurl4-openssl-dev
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
//判断文件是否存在
int checkRemoteRuleFileExist(const char * URL) {
CURL * curl_fd = curl_easy_init();
CURLcode code = -1;
CURLINFO response_code = 0;
curl_easy_setopt(curl_fd, CURLOPT_NOBODY, 1);
curl_easy_setopt(curl_fd, CURLOPT_TIMEOUT, 3);
curl_easy_setopt(curl_fd, CURLOPT_URL, URL);
code = curl_easy_perform(curl_fd);
if (code == CURLE_OK) {
curl_easy_getinfo(curl_fd, CURLINFO_RESPONSE_CODE, &response_code);
}
curl_easy_cleanup(curl_fd);
return response_code;
}
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
int main()
{
char *url = "http://127.0.0.1/test.html";
if(checkRemoteRuleFileExist(url) == 404)
{
printf("file not existff\n");
}
CURL *curl;
FILE *fp;
CURLcode res;
char outfilename[FILENAME_MAX] = "./test.html";
curl = curl_easy_init();
if (curl) {
fp = fopen(outfilename,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
fclose(fp);
}
return 0;
}
编译:
gcc main.c -lcurl
网友评论