Difference between revisions of "Reading and writing to files"

From D Wiki
Jump to: navigation, search
(One line recipes)
 
(add description)
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
=== Reading and writing to files ===
+
== Reading and writing to files ==
 +
 
 +
A collection of one handy snippets for reading, manipulating and writing data to files in one line.
  
 
* Given a file with a single number on each line, reach only the first 10 lines, sum the total and print each number read.
 
* Given a file with a single number on each line, reach only the first 10 lines, sum the total and print each number read.
Line 31: Line 33:
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
 +
[[Category:Cookbook]]

Latest revision as of 23:10, 17 July 2020

Reading and writing to files

A collection of one handy snippets for reading, manipulating and writing data to files in one line.

  • Given a file with a single number on each line, reach only the first 10 lines, sum the total and print each number read.
module read_and_sum;

import std.conv : to;
import std.stdio: writeln;
import std.range : takeExactly, tee;
import std.algorithm.iteration : map, each;

void main()
{
    double total = 0;
    File("./10numbers.txt")
         // lazily iterate by line
        .byLine

         // pick first 10 lines
        .takeExactly(10)
         
         // convert each to double
        .map!(to!double)

         // add element ro total
        .tee!((x) { total += x; })

        // print each number 
        .each!writeln;
}