温馨提示×

c++中curl库的使用案例

c++
小樊
102
2024-08-11 05:10:35
栏目: 编程语言

#include #include <curl/curl.h>

//回调函数,将获取到的数据输出到控制台 size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream) { size_t written = fwrite(ptr, size, nmemb, (FILE *)stream); return written; }

int main() { CURL *curl; FILE *fp; CURLcode res;

//初始化curl
curl = curl_easy_init();
if (curl) {
    //设置URL
    curl_easy_setopt(curl, CURLOPT_URL, "https://www.example.com");

    //打开文件,将获取的数据写入到文件中
    fp = fopen("output.html", "wb");
    if (fp) {
        //设置回调函数
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        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));
        }

        //关闭文件
        fclose(fp);
    }

    //清理curl
    curl_easy_cleanup(curl);
}

return 0;

}

0