The D programming language does not differentiate between binary or text files. This is because a file represents a sequence of bytes.
This Answer discusses how to manipulate files in D.
As soon as a program executes, the input and output streams are operational. However, we must specify the name and the rights to that file to open and then manipulate it.
To open a file, we use the following code:
File file = File(filepath, "access-mode");
filepath
is the path to the file we need to open.access-mode
is the type of access we need.r
opens the file in reading mode.r+
opens the file in reading and writing mode.w
opens the file in writing mode. It creates the file if it doesn’t exist.w+
opens the file in reading and writing mode. It creates the file if it doesn’t exist. If the file already exists, it truncates the file to zero.a
opens the file in appending mode. The contents to be written are appended after the already existing contents of the file. If the file doesn’t exist, it creates the file first.a+
opens the file in reading and writing mode. The contents to be written are appended after the already existing contents of the file. However, the reading starts from the beginning. If the file doesn’t exist, it creates the file first.To close a file, we use the following code:
file.close();
We read a single line from an open file like this:
string line = file.readln();
We write a line in an open file like this:
file.writeln("Welcome to Educative");
import std.stdio; import std.file; void main() { File file; /* Writing a file */ file= File("d_lang.txt", "w"); file.writeln("Welcome to Educative"); file.close(); /* Reading a file*/ file = File("d_lang.txt", "r"); string line = file.readln(); writeln(line); file.close(); }
d_lang
doesn’t exist, we create it. We then write in the file.d_lang
file.RELATED TAGS
CONTRIBUTOR
View all Courses