Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Base64 Decoding

Part of StandardLibraryCategory

Description

This example shows how to convert base64 text file into a binary file using std.base64.

Purpose

Converts base64 encoded files found at the web interface (such as the main D newsgroup) to the D newsgroup into binary files. (I tested it with D:22264.)

Instructions

Save the page that includes the base64 encoding as something like "post.html". Call this program as "b64_to_bin.exe post.html". Rename "post.html.bin" to whatever the file name should be.

Limitation

This routine only captures the first file if more than one is attached.

Example

import std.base64;
import std.c.stdio;
import std.string;
import std.stream;

void main(char[][] args)
{
    if (args.length > 1)
    {
        File b64_file = new File(args[1]);
        char[] line_in;
        printf("Processing (%.*s)...\n", args[1]);
        while (!b64_file.eof())
        {
            line_in = b64_file.readLine();
            if (tolower(line_in) == "content-transfer-encoding: base64<br>")
            {
                char[] content;

                printf("Base64 content found...\n");
                line_in = b64_file.readLine();
                line_in = b64_file.readLine();
                line_in = b64_file.readLine();
    
                line_in = line_in[9..line_in.length];            
                while(line_in != "</pre>")
                {
                    content ~= line_in;
                    line_in = b64_file.readLine();
                }

                char[] decoded_content = decode(content);

                File output = new File();
                output.create(args[1] ~ ".bin", FileMode.Out);
                output.writeBlock(decoded_content, decoded_content.length);
                output.close();
                printf("File saved as %.*s.bin\n\n", args[1]);
            }
        }            
    }
    else
        printf("\nb64_to_bin:\nUsage: b64_to_bin [filename to process]\n\n");
}