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

Reading Files at Compile Time

Description

D lets you do a lot code execution during compile time, also known as Compile Time Function Evaluation (CTFE). Sometimes the information you want to work with at compile time is located in a file, you can access the content by using import("filename"); which returns a character array.

Example

File: ctfi.txt

Hello World

File: ctfi.d

import std.stdio;

void main() {
	const foo = import("ctfi.txt");

	writefln(foo);
}

If you try to compile this with $ dmd ctfi.d you will receive the error

ctfi.d(6): Error: need -Jpath switch to import text file ctfi.txt

This is the path for file imports that are not libraries. Use the following for compilation:

Compile:

dmd -J. ctfi.d