Sunday, May 15, 2016

[DLang]: A simple file download utility in D

By Vasudev Ram

Download image attribution

Hi readers,

Here is another in my recently started series of posts about D (DLang / the D language).

This is a simple download utility written in D, to download a file from a URL.

It makes use of a high-level function called download (sic) in the module, so the code is very simple. But it only handles basic cases; e.g. no authentication or HTTPS support.
File: download.d
Version: 0.1
Purpose: A simple program to download a file from a given URL 
to a given local file. Only handles simple cases. Does not  
support authentication, HTTPS or other features.
Author: Vasudev Ram -
Copyright 2016 Vasudev Ram

import std.stdio;

void usage(string program)
    writeln("Usage: ", program, " URL file");
    writeln("Downloads the contents of URL to file.");

int main(string[] args)
    if (args.length != 3)
        return 1;
        writeln("Trying to download (URL) ", args[1], " to (file) ", args[2]);
        download(args[1], args[2]);
        writeln("Item at URL ", args[1], " downloaded to file ", args[2]);
        return 0;
    catch(Exception e)
        writeln("Error: ", e.msg);
        debug(1) writeln("Exception info:\n", e);
        return 1;
A makefile to build it in both debug and release versions:
$ type Makefile

release: download.d
        dmd -ofdownload.exe download.d

debug: download.d
        dmd -debug -ofdownload.exe download.d
To build the release version:
make release
To build the debug version:
make debug
A test run: download the current HN home page:
download nyc.html
Output is in nyc.html; see screenshot below:

The line:
debug(1) writeln("Exception info:\n", e);
gets compiled into the binary / EXE only if you build the debug version.
That line prints a bit more information about the exception than the release version does.

You can also read a few posts about downloading using Python tools.

- Enjoy.

- Vasudev Ram - Online Python training and consulting

Signup to hear about my new courses and products.

My Python posts     Subscribe to my blog by email

My ActiveState recipes

No comments: