Curl在C -Store中获取请求将html数据存储在另一个文件中

时间:2015-04-16 13:26:29

标签: c curl

我正在使用此代码使用c语言中的curl请求从Web浏览器中检索数据。我想将输出存储在另一个文件或缓冲区中。

#include <stdio.h>
#include <curl/curl.h>
#include <curl/easy.h>
int main(void)
{
  CURL *curl;
  CURLcode res;

  curl = curl_easy_init();
  if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
/* example.com is redirected, so we tell libcurl to follow redirection */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
  fprintf(stderr, "curl_easy_perform() failed: %s\n",
          curl_easy_strerror(res));

/* always cleanup */
curl_easy_cleanup(curl);
 }
return 0;
}

此代码的输出是一个html文件。我想将html存储在另一个文件或缓冲区中。怎么做。

提前谢谢。

1 个答案:

答案 0 :(得分:2)

这是对代码的修改,它将HTML响应写入文件:

#include <stdio.h>
#include <curl/curl.h>
#include <curl/easy.h>
int main(void)
{
    CURL *curl;
    CURLcode res;

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");

        /* example.com is redirected, so we tell libcurl to follow redirection */
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

        /* create an output file and prepare to write the response */
        FILE *output_file = fopen("output_file.html", "w");
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, output_file);

        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);

        /* Check for errors */
        if(res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %sn", 
                curl_easy_strerror(res));
        }

        /* always cleanup */
        curl_easy_cleanup(curl);
    }
    return 0;
}

以下是一些相关问题:

Saving a file using libcurl in C

Download file using libcurl in C/C++