Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

d
file manipulation

How to manipulate files in D

Zain Babar

Overview

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.

Opening and closing files

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.

Modes

  1. r opens the file in reading mode.
  2. r+ opens the file in reading and writing mode.
  3. w opens the file in writing mode. It creates the file if it doesn’t exist.
  4. 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.
  5. 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.
  6. 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();

Reading and writing in a file

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");

Example

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();
}
Writing and reading from a file in D

Explanation

  • Line 7: We write in a file. Since a file named d_lang doesn’t exist, we create it. We then write in the file.
  • Line 9: We close the d_lang file.
  • Line 12: We open the recently written file and read it.
  • Line 14: We display the output of the text read from the file. We then close the file.

RELATED TAGS

d
file manipulation

CONTRIBUTOR

Zain Babar
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring