Saving a file using libcurl in C

2019-02-13 21:30发布

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

1条回答
虎瘦雄心在
2楼-- · 2019-02-13 22:09

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++

查看更多
登录 后发表回答