Writing Files in D Programming Language

Here’s the translation of the Go code to D Programming Language, formatted in Markdown suitable for Hugo:

Writing files in D follows similar patterns to the ones we saw earlier for reading.

import std.stdio;
import std.file;
import std.exception;

void check(string err) {
    if (err) {
        throw new Exception(err);
    }
}

void main() {
    // To start, here's how to dump a string (or just bytes) into a file.
    string content = "hello\nD\n";
    std.file.write("/tmp/dat1", content);

    // For more granular writes, open a file for writing.
    auto f = File("/tmp/dat2", "w");

    // It's idiomatic to use scope(exit) for cleanup
    scope(exit) f.close();

    // You can write byte arrays as you'd expect.
    ubyte[] d2 = [115, 111, 109, 101, 10];
    auto n2 = f.rawWrite(d2);
    writefln("wrote %d bytes", n2);

    // A writeln is also available for strings.
    auto n3 = f.writeln("writes");
    writefln("wrote %d bytes", n3);

    // Issue a flush to ensure writes are committed to stable storage.
    f.flush();

    // std.stdio provides buffered writers in addition
    // to the buffered readers we saw earlier.
    auto w = f.lockingTextWriter();
    auto n4 = w.put("buffered\n");
    writefln("wrote %d bytes", n4);

    // Use flush to ensure all buffered operations have
    // been applied to the underlying writer.
    f.flush();
}

Try running the file-writing code.

$ dmd -run writing-files.d
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

$ cat /tmp/dat1
hello
D
$ cat /tmp/dat2
some
writes
buffered

Next we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin and stdout streams.