user Ammu
user Ammu

Reputation: 35

Curl get request in C -Store the html data in another file

I am using this code to retrieve the data from the web browser using curl request in c language. I want to store the output in another file or buffer.

#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;
}

The output of this code is an html file. I want to store that html in another file or buffer. How to do that.

Thank you in advance.

Upvotes: 0

Views: 1651

Answers (1)

rphv
rphv

Reputation: 5537

Here's a modification to your code that writes the HTML response to a file:

#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;
}

Here are some related questions:

Saving a file using libcurl in C

Download file using libcurl in C/C++

Upvotes: 2

Related Questions