2014-01-10 52 views
0

嗨我試圖保存CURL服務器的響應,並得到以下錯誤: 我讀到這是由於讀取數據和寫入文件的大小不同,所以捲曲是粉碎。文件被創建幷包含需要XML數據但仍顯示錯誤。感謝您的幫助!!「寫入正文和數據失敗」libcurl C++

  • 失敗書寫體(0 = 96!)

  • 無法寫入數據

  • 關閉連接#0

這裏是我的CB功能:

static size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) 
{ size_t written = fwrite(ptr, size, nmemb, stream); return written; } 

和方法:

createJob(標準::字符串s的std :: string目錄){

static const char *fp = "resultcurl.xml"; 
    std::stringstream filepath; 
filepath<< directory; 
    filepath<< fp; 

    std::string pagefilename = filepath.str(); 

FILE *pagefile; 
    std::string job_id; 

struct curl_slist *headers = NULL; 

std::string jobXML = s; 
curl = curl_easy_init(); 

if (curl) { 

    headers = curl_slist_append(headers, "Accept: */*"); 
    headers = curl_slist_append(headers, "Content-Type: application/xml"); 
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 
    curl_easy_setopt(curl, CURLOPT_VERBOSE, true); 

    curl_easy_setopt(curl, CURLOPT_URL, 
      ".../jobs.xml"); 

    curl_easy_setopt(curl, CURLOPT_USERPWD, "..."); 

    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jobXML.c_str()); 
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(jobXML.c_str())); 

    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,write_data); 

      pagefile = fopen(pagefilename.c_str(), "wb"); 

     if (pagefile) { 


      curl_easy_setopt(curl, CURLOPT_FILE, pagefile); 

      //curl_easy_perform(curl); 


      } 

      res = curl_easy_perform(curl); 

      /* cleanup curl stuff */ 
      curl_easy_cleanup(curl); 

      //job_id =readXMLvalue(pagefilename); 
      fclose(pagefile); 
      return 0; 

} 
+1

相同的錯誤也與CURLOPT_WRITEDATA – user3082058

+0

抱歉,我忘了經證明的所有方法。它有文件路徑,文件包含數據:o不是空的。這讓我感到困惑。 – user3082058

回答

2

交換設置的順序,

pagefile = fopen(pagefilename.c_str(), "wb"); 
    if (pagefile) { 
     curl_easy_setopt(curl, CURLOPT_FILE, pagefile); 
     curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,write_data); 
     ... 
    } 
    ... 
+0

tnx它的工作原理如果我把寫函數放在if部分 – user3082058

0

如果你只想寫數據放入文件中,Curl會爲你做。設置

if(curl_easy_setopt(curl , CURLOPT_WRITEDATA , (void *) fptr ) != CURLE_OK) 
{ 
    return(YOUR_ERR_CODE) ; 
} 

其中FPTR是,

FILE *fptr = fopen("emalware.127.5a6ceb78050f80e4c833dcc3764bf9dd.gzip", "wb"); 
if(fptr == NULL) 
{ 
    return -1; 
}