Reading Files in D Programming Language

Our first example demonstrates reading files in D. Reading and writing files are basic tasks needed for many D programs. Let’s look at some examples of reading files.

import std.stdio;
import std.file;
import std.string;

// Reading files requires checking most calls for errors.
// This helper will streamline our error checks below.
void check(string msg)
{
    if (msg)
    {
        throw new Exception(msg);
    }
}

void main()
{
    // Perhaps the most basic file reading task is
    // slurping a file's entire contents into memory.
    string dat = readText("/tmp/dat");
    writeln(dat);

    // You'll often want more control over how and what
    // parts of a file are read. For these tasks, start
    // by opening a file to obtain a File object.
    auto f = File("/tmp/dat", "r");

    // Read some bytes from the beginning of the file.
    // Allow up to 5 to be read but also note how many
    // actually were read.
    char[5] b1;
    auto n1 = f.rawRead(b1);
    writefln("%d bytes: %s", n1.length, n1);

    // You can also seek to a known location in the file
    // and read from there.
    f.seek(6);
    char[2] b2;
    auto n2 = f.rawRead(b2);
    writefln("%d bytes @ %d: %s", n2.length, 6, n2);

    // The std.stdio package provides some functions that may
    // be helpful for file reading. For example, reads
    // like the ones above can be more robustly
    // implemented with readln.
    f.seek(0);
    string line = f.readln();
    writefln("Read line: %s", line.chomp());

    // There is no built-in rewind, but
    // seek(0) accomplishes this.
    f.seek(0);

    // The std.stdio package implements a buffered
    // reader that may be useful both for its efficiency
    // with many small reads and because of the additional
    // reading methods it provides.
    auto r4 = f.byLine();
    writefln("First line: %s", r4.front);

    // Close the file when you're done (usually this would
    // be scheduled immediately after opening with
    // scope(exit)).
    f.close();
}

To run the program, first create a test file:

$ echo "hello" > /tmp/dat
$ echo "d" >>   /tmp/dat
$ rdmd reading_files.d
hello
d
5 bytes: hello
2 bytes @ 6: d
Read line: hello
First line: hello

This example demonstrates various methods of reading files in D, including reading entire files, reading specific bytes, seeking to positions in the file, and using buffered readers. The D standard library provides robust tools for file I/O operations, making it straightforward to work with files in your programs.

Next, we’ll look at writing files.