5

I'm expanding from perl to C and I'm trying to use curl's library to simply save a file from a remote url but I'm having a hard time finding a good example to work from.

Also, I'm not sure if I should be using curl_easy_recv or curl_easy_perform

273K
  • 29,503
  • 10
  • 41
  • 64
Pat
  • 51
  • 1
  • 1
  • 2

1 Answers1

6

I find this resource very developer friendly.

I compiled the source code below with:

gcc demo.c -o demo -I/usr/local/include -L/usr/local/lib -lcurl

Basically, it will download a file and save it on your hard disk.

File demo.c

#include <curl/curl.h>
#include <stdio.h>

void get_page(const char* url, const char* file_name)
{
  CURL* easyhandle = curl_easy_init();

  curl_easy_setopt( easyhandle, CURLOPT_URL, url ) ;

  FILE* file = fopen( file_name, "w");

  curl_easy_setopt( easyhandle, CURLOPT_WRITEDATA, file) ;

  curl_easy_perform( easyhandle );

  curl_easy_cleanup( easyhandle );

  fclose(file);

}

int main()
{
  get_page( "http://blog.stackoverflow.com/wp-content/themes/zimpleza/style.css", "style.css" ) ;

  return 0;
}

Also, I believe your question is similar to this one:

Download file using libcurl in C/C++

Community
  • 1
  • 1
karlphillip
  • 92,053
  • 36
  • 243
  • 426
  • Whenever I do this, I get the headers at the top of my file that I save to. Is there a way to get around this? `HTTP/1.1 200 OK Server: nginx/1.4.1 Date: Thu, 01 May 2014 16:56:21 GMT Content-Type: text/html; charset=utf-8 Content-Length: 7625 Connection: keep-alive` – srchulo May 01 '14 at 17:05
  • never mind. I found the solution here: http://stackoverflow.com/questions/5142869/how-to-remove-http-headers-from-curl-response – srchulo May 01 '14 at 18:16