Search code examples
terminalpipedio-redirection

Redirecting from command line to a D program


I want to redirect a .txt file from the command line into an exetuable written in D.

$ ./myprogram < data.txt

This text file consist of numbers that I want to print to the screen. So far, my program consists of this:

import std.stdio, std.file;

void main(string[] args) {

    string file = args[2];
    writeln(read(file));
}

But this is not correct; could someone explain me how redirects work and how I transfer the data in to my D program?


Solution

  • You can use stdin to read input like that:

    import std.stdio, std.file;
    
    void main(string[] args)
    {
        foreach (line; stdin.byLine())
        {
            writeln(line);
        }
    }