Importing Text Files

In this lesson, you will learn about how mixins can be used for importing text files.

We'll cover the following

Inserting contents of text files

It is possible to insert contents of text files into code at compile time. The contents are treated as string literals and can be used anywhere strings can be used. For example, they can be mixed in as code. For example, let’s assume there are two text files on the file system named file_one and file_two that have the following contents.

  • file_one:

    Hello
    
  • file_two:

    s ~= ", World!"; 
    import std.stdio; 
    writeln(s);
    

The two import directives in the following program would correspond to the contents of those files converted to string literals at compile time:

void main() {
    string s = import ("file_one");
    mixin (import ("file_two")); 
}

Text file imports (aka string imports) require the -J compiler switch, which tells the compiler where to find the text files. For example, if the two files are in the current directory (specified with . in Linux environments), the program can be compiled with the following command:

$ dmd -J. main.d

The output is:

Hello, World!

Furthermore, considering the mixed-in string, the program is the equivalent of the following one:

Get hands-on with 1000+ tech skills courses.