how to use curl to download a file

Graham Fawcett fawcett at uwindsor.ca
Wed Nov 2 08:09:17 PDT 2011


On Tue, 01 Nov 2011 18:20:25 +0000, Frédéric Galusik wrote:

> Hi,
> 
> As the curl documentation is a little bit ...wow.
> http://www.digitalmars.com/d/2.0/phobos/etc_c_curl.html
> 
> Do someone have a simple example on how to download a simple file ?
> 
> Thank you.

Until the high-level bindings for curl are available in Phobos, I have a 
little module you could use.

https://github.com/gmfawcett/d-play-libcurl/blob/master/fawcett/curl.d

The default version prints the result to stdout, and there's a commented 
main() that shows how to get a callback when data is received. If you 
wanted to download directly into a file, you could do this:

import std.stdio;
import fawcett.curl;

class FileCurl : Curl 
{
  this(string url, File f) {
    handle = curl_easy_init();
    set(CURLoption.URL, url);
    set(CURLoption.FILE, cast(void*) f.getFP);
  }

}

void main() {
  auto f = File("/tmp/stuff", "w");
  auto c = new FileCurl("http://example.com/", f);
  c.perform();
}

Note, it doesn't call super() in the constructor, which is bad form, but 
the current default constructor is overkill for just downloading a file. 
(It's not a production-quality curl binding.)

Rather than putting my module in 'fawcett/curl.d', you might just want to 
remove the 'module' line in 'curl.d' and put it in the same directory as 
your program.

Best,
Graham




More information about the Digitalmars-d-learn mailing list