byLine

Returns an input range set up to read from the file handle one line at a time.

The element type for the range will be Char[]. Range primitives may throw StdioException on I/O error.

Note: Each front will not persist after popFront is called, so the caller must copy its contents (e.g. by calling to!string) when retention is needed. If the caller needs to retain a copy of every line, use the byLineCopy function instead.

  1. auto byLine(KeepTerminator keepTerminator = No.keepTerminator, Terminator terminator = '\n')
    byLine
    (
    Terminator = char
    Char = char
    )
    (
    KeepTerminator keepTerminator = No.keepTerminator
    ,
    Terminator terminator = '\n'
    )
    if (
    isScalarType!Terminator
    )
  2. auto byLine(KeepTerminator keepTerminator, Terminator terminator)

Parameters

Char

Character type for each line, defaulting to char.

keepTerminator

Use Yes.keepTerminator to include the terminator at the end of each line.

terminator
Type: Terminator

Line separator ('\n' by default). Use std.ascii.newline for portability (unless the file was opened in text mode).

Examples

1 import std.algorithm, std.stdio, std.string;
2 // Count words in a file using ranges.
3 void main()
4 {
5     auto file = File("file.txt"); // Open for reading
6     const wordCount = file.byLine()            // Read lines
7                           .map!split           // Split into words
8                           .map!(a => a.length) // Count words per line
9                           .sum();              // Total word count
10     writeln(wordCount);
11 }
1 import std.range, std.stdio;
2 // Read lines using foreach.
3 void main()
4 {
5     auto file = File("file.txt"); // Open for reading
6     auto range = file.byLine();
7     // Print first three lines
8     foreach (line; range.take(3))
9         writeln(line);
10     // Print remaining lines beginning with '#'
11     foreach (line; range)
12     {
13         if (!line.empty && line[0] == '#')
14             writeln(line);
15     }
16 }

Notice that neither example accesses the line data returned by front after the corresponding popFront call is made (because the contents may well have changed).

Meta

Suggestion Box / Bug Report