溫馨提示×

c++中curl庫的使用案例

c++
小樊
100
2024-08-11 05:10:35
欄目: 編程語言

#include #include <curl/curl.h>

//回調(diào)函數(shù),將獲取到的數(shù)據(jù)輸出到控制臺 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) {
    //設(shè)置URL
    curl_easy_setopt(curl, CURLOPT_URL, "https://www.example.com");

    //打開文件,將獲取的數(shù)據(jù)寫入到文件中
    fp = fopen("output.html", "wb");
    if (fp) {
        //設(shè)置回調(diào)函數(shù)
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

        //執(zhí)行請求
        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                    curl_easy_strerror(res));
        }

        //關(guān)閉文件
        fclose(fp);
    }

    //清理curl
    curl_easy_cleanup(curl);
}

return 0;

}

0