This example is not as easy as "Hello World", but it gives an insight as to how D programs look and work.
Let's begin with a new project, called "fio.d", which checks the existance of a file and writes it to the output:
import std.stdio; import std.file;
int main(char[][] args)
{
char[] filename = "text.txt";
return 0;
} |
The first function we need is called exists. It is located in the "std.file" module and can be used like this:
if (exists(filename)!=0) {
} else {
} |
To read content from a file, we can use the function read and to get it's size, we use getSize, both are declared in "std.file" again.
To write to the console, we use the function writefln, which takes any number of arguments, including ones containing formatting codes.
import std.stdio;
import std.file;
int main(char[][] args)
{
char[] filename = "text.txt";
if (exists(filename)!=0) {
uint size = getSize(filename);
writefln("%s", cast(char[])read(filename));
writefln("");
writefln("Size of file = %d (bytes).",size);
} else {
writefln("File not found. Please try again later :-)");
}
return 0;
} |
That's all the tricks to displaying content. Well not quite... the line
writefln("%s", cast(char[])read(filename)); | needs a bit more explanation. The read function reads in the content of the file into a dynamic array of bytes; a byte[] type. However, the writefln does not know how to display an array of arbitary bytes. It does know how to display character strings though and an array of ASCII bytes is the same as a character string. So if your file only contains ASCII characters, you can tell D that the read function is returning a character array (a.k.a. a string). You do this by the cast syntax.
Also note that the first argument to the writefln call is a string containing a single formating code %s. This tells writefln that the next argument is to be displayed as a text string. If you didn't have this formating code, and the text file contained formating codes, writefln would crash as it would be expecting more arguments to match the formating codes embedded in the text file.
Now we will add one thing: If there is no file, the program should create one. We do this by calling write:
write(filename,"Well done!\n"~
"The file "~filename~" was written and read without problems.\n\n"~
"If you did understand this tutorial, the time has come to\n"~
"get in touch with the 'Language Reference' or the\n"~
"'standard runtime library', also called \"phobos\"."); |
Replace the comment in the code above ("/* File does not exist! */") with this call to the write function, compile and test it :-)
See also:
std.stdio, std.file
|