(1) reading a text file line by line
|
def main():
f = open("input.txt", "r")
for line in f:
line = line.rstrip("\r\n")
print(line)
f.close()
|
import std.stdio;
void main()
{
File f = File("input.txt", "r");
foreach (line; f.byLineCopy())
{
// line doesn't contain the newline character
writeln(line);
}
// f.close();
}
|
In D, when the variable f
goes out of scope, it's guaranteed that the file will be closed. Thus, calling f.close()
is not necessary. But, you can call it if you want. For instance, if you want to re-open a file, then first you'll have to close it manually and then you can open it again.
f.byLineCopy()
returns a string copy of the current line that can be stored.
f.byLine()
returns a slice on the inner buffer whose content changes as you read the lines. It's faster but line
is only valid in the current iteration, you cannot store it. byLineCopy()
is more secure.
(2) writing to a text file
|
def main():
f = open("out.txt", "w")
print("Hello, World!", file=f)
year = 2025
print(f"Current year: {year}", file=f)
print("END")
|
import std.stdio;
void main()
{
File f = File("out.txt", "w");
f.writeln("Hello, World!");
int year = 2025;
f.writefln("Current year: %s", year);
// f.close();
writeln("END");
}
|
$ cat out.txt
Hello, World!
Current year: 2025