File.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, Terminator terminator)
    struct File
    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 KeepTerminator

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

terminator Terminator

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

Examples

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

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