將返回的json字符串存入文件

#include <stdio.h>
#include <curl/curl.h>
#include <json/json.h>
#include <iostream>
#include <string>
#include <fstream>
#pragma warning(disable:4996)

//適當地使用size_t還會使你的代碼變得如同自帶文檔。
//它代表字節大小或數組索引。
size_t receive_data(void* buffer, size_t size, size_t nmemb, FILE* file) {
    size_t r_size = fwrite(buffer, size, nmemb, file);
    //該函數以二進制形式對文件進行操作,不侷限於文本文件。
    //將buffer所指向的數組中的數據寫入到file輸出流中。
    //size是被寫入的每個元素的大小,以字節爲單位,nmemb是元素的個數。
    //每個元素的大小是size字節。
    //返回值是實際寫入的數據項個數。
    //該函數僅僅只是把數據寫到了用戶空間緩存區,並未同步到文件。
    return r_size;
}

int main(void)
{
    CURL* curl;
    CURLcode res;
    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();   /* get a curl handle */
    if (curl) {
        //char path[] = "savefile.txt";
        //FILE* file = fopen(path, "w+");
        ////w+ 打開可讀寫文件,若文件存在則文件長度清爲零,即該文件內容會消失。若文件不存在則建立該文件。
        /* First set the URL that is about to receive our POST. This URL can
           just as well be a https:// URL if that is what should receive the
           data. */
        curl_easy_setopt(curl, CURLOPT_URL, "在這裏,輸入需要請求的網址即可。。");
        struct curl_slist* headers = NULL; /* init to NULL is important */
        headers = curl_slist_append(headers, "Content-Type:application/json");
        //這句話是設置格式。這裏面有很多種格式。要確認發送的格式滿足服務器的接口要求。
        /* pass our list of custom made headers */
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        const std::string jsonstring1 = "這裏面是一個json字符串。滿足要求的一個字符串。";
        const char* data = jsonstring1.c_str();
        //curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, -1);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(data));
        //curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonstring1);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
        /* Perform the request, res will get the return code */
        //curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, receive_data);
        //curl_easy_setopt(curl, CURLOPT_WRITEDATA, file);
        res = curl_easy_perform(curl);

        /* Check for errors */
        if (res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));
        //fclose(file);
        curl_slist_free_all(headers); /* free the header list */
        /* always cleanup */
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章