Programming Search⌘K

Taskcore

Read a file line by line

Also called iterate over the lines of a file, read lines from a text file, stream a text file.

Read a UTF-8 text file one line at a time, with only the current line in memory, and report an error for a missing file or bad bytes.

Task

Read a text file one line at a time. Keep only the current line in memory, so the file can be larger than the memory.

So that the tests can check the result, each solution returns two numbers: the number of lines, and the number of Unicode code points in the longest line. The line terminator is not part of a line.

The file is UTF-8 with no byte order mark. A line ends with LF (\n) or CRLF (\r\n). A CR alone does not occur. The last line can have no terminator, and it is still a line. An empty file has no lines, so the result is (0, 0). A file that holds only \n has one empty line.

A solution must accept a line of 1 MiB or more. It can refuse a longer line, but then it reports an error.

If the file does not exist, or its bytes are not valid UTF-8, the solution reports an error and returns no result. It must not put U+FFFD in place of the bad bytes and continue.

SQL, regular expressions, HTML and CSS do not apply, because none of them can open a file and loop over it.

Solutions

Each solution reads the file through a buffer and handles one line in each step of a loop.

  • Python. for line in file reads one line per step. Give encoding="utf-8", because before Python 3.15 the default encoding comes from the locale. The default newline=None changes \r\n to \n, so the code removes only \n.
  • JavaScript and TypeScript (Node.js). A for await loop over readline.createInterface on fs.createReadStream, with crlfDelay: Infinity. The bytes go through a TextDecoder with fatal: true first, because readline puts U+FFFD in place of bad bytes. The TypeScript file adds types only. It uses async iteration.
  • Java. Files.lines(path) decodes UTF-8 and fills the stream lazily. Put it in try-with-resources, so the file closes. A read error comes out of the stream as UncheckedIOException, and the solution throws its cause.
  • Kotlin. Path.useLines gives a lazy sequence of lines and closes the file at the end. It reads with Files.newBufferedReader, so bad bytes cause a MalformedInputException.
  • C#. File.ReadLines returns the lines one by one. Give it new UTF8Encoding(false, true), because the default decoder replaces bad bytes. EnumerateRunes counts code points, not UTF-16 units.
  • Go. bufio.Scanner with ScanLines removes \n and one \r before it. Call Buffer to raise the limit, and call Err after the loop. The scanner does not decode, so the code calls utf8.Valid on each line.
  • Rust. BufReader::new(File::open(path)?).lines() gives one io::Result<String> per line, without \n or \r\n. Bytes that are not UTF-8 give an error of kind InvalidData.
  • C. POSIX getline grows one buffer to the longest line and returns -1 at the end or on an error. ferror tells the two apart. The code removes \n and \r, and checks the UTF-8 itself.
  • C++. while (std::getline(in, line)) on a binary std::ifstream. The code removes a final \r, checks the UTF-8 itself, and returns std::expected (C++23).
  • Bash (4.4 or later). while IFS= read -r line || [[ -n $line ]] reads from iconv -f UTF-8 -t UTF-8, which stops on bad bytes. wait $! gets the status of iconv. In a UTF-8 locale, ${#line} counts characters.
  • PowerShell. foreach over [System.IO.File]::ReadLines with a strict UTF8Encoding. Get-Content also sends one line at a time, but it replaces bad bytes. .NET resolves a relative path from the process directory, so the code resolves it from the current location first.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl, with one file for each in fixtures/. The cases that must give an error are in cases/errors.jsonl.

  • empty: no bytes. The result is (0, 0), not (1, 0).
  • only-newline: one empty line, so the result is (1, 0).
  • no-final-newline and crlf-no-final-newline: the last line has no terminator. Many loops lose it.
  • crlf and mixed-endings: if the \r stays, each length is one too large.
  • whitespace: leading and trailing blanks and a tab are part of the line. Bash read without IFS= removes them.
  • backslashes: Bash read without -r removes the backslashes.
  • long-line: one line of 1 MiB, more than the default limit of the Go scanner.
  • non-ascii: characters of 2, 3 and 4 bytes. The emoji is 4 bytes in UTF-8 and 2 units in UTF-16, but 1 code point.
  • Errors: a missing file, the bytes FF FE, a sequence cut by the end of the file, an encoded surrogate (ED A0 80) and an overlong form (C0 AF). RFC 3629 does not allow these bytes.

Pitfalls

  • The lost last line in Bash. At the end of the file, read returns a nonzero status, but it still sets the variable. So while read drops a last line that has no \n:

This code runs but gives a wrong answer on purpose.

printf 'one\ntwo' | while IFS= read -r line; do echo "got: $line"; done
Output
got: one

Add || [[ -n $line ]] to the condition:

printf 'one\ntwo' | while IFS= read -r line || [[ -n $line ]]; do echo "got: $line"; done
Output
got: one
got: two
  • The 64 KiB limit of the Go scanner. By default a token can be at most bufio.MaxScanTokenSize bytes. On a longer line Scan returns false, as at the end of the file. Only Err tells you that the scanner stopped early:
package main

import (
	"bufio"
	"fmt"
	"strings"
)

func main() {
	text := "short\n" + strings.Repeat("x", 70000) + "\nlast\n"
	s := bufio.NewScanner(strings.NewReader(text))
	lines := 0
	for s.Scan() {
		lines++
	}
	fmt.Println("lines:", lines)
	fmt.Println("error:", s.Err())
}
Output
lines: 1
error: bufio.Scanner: token too long
  • Methods that read the whole file. Python file.readlines() and list(file), Java Files.readAllLines and C# File.ReadAllLines make a list of all the lines. Loop over the lines instead.
  • A trailing \r with CRLF. The Go scanner, Rust lines, Python, Java and .NET remove it. C getline, C++ std::getline and Bash read keep it, so the code must remove it. Node.js readline can see \r and \n as two line ends if they arrive more than crlfDelay milliseconds apart.
  • Silent replacement of bad bytes. Node.js readline, PowerShell Get-Content, C# File.ReadLines(path) and Kotlin File.bufferedReader put U+FFFD in place of bad bytes and give no error. Python before 3.15 uses the locale encoding, so a UTF-8 file can decode with the wrong encoding and give no error.
  • feof loops in C. while (!feof(f)) tests for the end before the read. feof becomes true only after a read fails, so the loop body runs once more with the old line. Test the return value of getline or fgets.

Code

The build runs the native tests of each language in a pinned toolchain.

line_stats.pyI0tests passRawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-file-line-by-line/.

import os


def line_stats(path: str | os.PathLike[str]) -> tuple[int, int]:
    """Return the number of lines and the code points in the longest line."""
    lines = longest = 0
    # The default newline=None turns "\r\n" into "\n".
    with open(path, encoding="utf-8") as file:
        for line in file:
            lines += 1
            longest = max(longest, len(line.removesuffix("\n")))
    return lines, longest
test_line_stats.py 51 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-file-line-by-line/.

from pathlib import Path

import pytest

from line_stats import line_stats

CASES = {
    "lf": (b"alpha\nbeta\ngamma\n", (3, 5)),
    "blank-lines": (b"first\n\n\nlast line\n", (4, 9)),
    "empty": (b"", (0, 0)),
    "only-newline": (b"\n", (1, 0)),
    "no-final-newline": (b"one\ntwo\nthree", (3, 5)),
    "crlf": (b"one\r\ntwo\r\nthree\r\n", (3, 5)),
    "crlf-no-final-newline": (b"one\r\ntwo\r\nthree", (3, 5)),
    "mixed-endings": (b"one\r\ntwo\nthree\r\n", (3, 5)),
    "whitespace": (b"  two spaces\ttab \n", (1, 17)),
    "backslashes": (b"C:\\temp\\new\n", (1, 11)),
    "long-line": (b"x" * (1 << 20) + b"\nend\n", (2, 1 << 20)),
    "non-ascii": ("naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n".encode(), (3, 10)),
}

INVALID_UTF8 = {
    "invalid-byte": b"ok\n\xff\xfe\n",
    "truncated-at-end": b"ok\ncaf\xc3",
    "encoded-surrogate": b"a\xed\xa0\x80b\n",
    "overlong": b"\xc0\xaf\n",
}


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
    data, want = CASES[name]
    path = tmp_path / "input.txt"
    path.write_bytes(data)
    assert line_stats(path) == want


def test_missing_file(tmp_path: Path) -> None:
    with pytest.raises(FileNotFoundError):
        line_stats(tmp_path / "missing.txt")


@pytest.mark.parametrize("name", INVALID_UTF8)
def test_invalid_utf8(tmp_path: Path, name: str) -> None:
    path = tmp_path / "input.txt"
    path.write_bytes(INVALID_UTF8[name])
    with pytest.raises(UnicodeDecodeError):
        line_stats(path)
line_stats.cppI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.
// since: C++23 (std::expected)

#include "line_stats.hpp"

#include <algorithm>
#include <fstream>
#include <optional>
#include <string>
#include <string_view>

namespace {

// Returns the number of code points of s, or nothing when s is not valid
// UTF-8 (RFC 3629): no overlong form, no surrogate, nothing above U+10FFFF.
std::optional<std::size_t> utf8_count(std::string_view s) {
    std::size_t count = 0;
    for (std::size_t i = 0; i < s.size(); ++count) {
        auto c = static_cast<unsigned char>(s[i]);
        std::size_t len = 0;
        unsigned char lo = 0x80, hi = 0xBF;  // the range of the second byte
        if (c < 0x80) {
            ++i;
            continue;
        } else if (c >= 0xC2 && c <= 0xDF) {
            len = 2;
        } else if (c >= 0xE0 && c <= 0xEF) {
            len = 3;
            if (c == 0xE0) lo = 0xA0;
            if (c == 0xED) hi = 0x9F;
        } else if (c >= 0xF0 && c <= 0xF4) {
            len = 4;
            if (c == 0xF0) lo = 0x90;
            if (c == 0xF4) hi = 0x8F;
        } else {
            return std::nullopt;
        }
        if (s.size() - i < len) return std::nullopt;
        auto second = static_cast<unsigned char>(s[i + 1]);
        if (second < lo || second > hi) return std::nullopt;
        for (std::size_t j = 2; j < len; ++j) {
            if ((static_cast<unsigned char>(s[i + j]) & 0xC0) != 0x80) return std::nullopt;
        }
        i += len;
    }
    return count;
}

}  // namespace

std::expected<LineStats, ReadError> line_stats(const std::filesystem::path& path) {
    // Binary mode gives the same bytes on every system; the code removes the '\r' itself.
    std::ifstream in(path, std::ios::binary);
    if (!in) return std::unexpected(ReadError::cannot_open);
    LineStats stats;
    std::string line;
    while (std::getline(in, line)) {  // removes the '\n'
        if (line.ends_with('\r')) line.pop_back();
        auto count = utf8_count(line);
        if (!count) return std::unexpected(ReadError::invalid_utf8);
        ++stats.lines;
        stats.longest = std::max(stats.longest, *count);
    }
    if (in.bad()) return std::unexpected(ReadError::read_failed);
    return stats;
}
line_stats.hpp 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.
// since: C++23 (std::expected)

#pragma once

#include <cstddef>
#include <expected>
#include <filesystem>

struct LineStats {
    std::size_t lines = 0;
    std::size_t longest = 0;  // in code points
    bool operator==(const LineStats&) const = default;
};

enum class ReadError { cannot_open, invalid_utf8, read_failed };

// Reads the UTF-8 text file at path line by line.
std::expected<LineStats, ReadError> line_stats(const std::filesystem::path& path);
test_line_stats.cpp 78 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include "line_stats.hpp"

namespace {

const std::filesystem::path input = "line_stats_input.txt";

void write_file(std::string_view data) {
    std::ofstream out(input, std::ios::binary);
    out << data;
}

int failures = 0;

void check(std::string_view name, bool ok) {
    if (!ok) {
        std::fprintf(stderr, "case %.*s failed\n", static_cast<int>(name.size()), name.data());
        ++failures;
    }
}

}  // namespace

int main() {
    using namespace std::string_literals;
    struct Case {
        std::string name, data;
        LineStats want;
    };
    const std::vector<Case> cases = {
        {"lf", "alpha\nbeta\ngamma\n", {3, 5}},
        {"blank-lines", "first\n\n\nlast line\n", {4, 9}},
        {"empty", "", {0, 0}},
        {"only-newline", "\n", {1, 0}},
        {"no-final-newline", "one\ntwo\nthree", {3, 5}},
        {"crlf", "one\r\ntwo\r\nthree\r\n", {3, 5}},
        {"crlf-no-final-newline", "one\r\ntwo\r\nthree", {3, 5}},
        {"mixed-endings", "one\r\ntwo\nthree\r\n", {3, 5}},
        {"whitespace", "  two spaces\ttab \n", {1, 17}},
        {"backslashes", "C:\\temp\\new\n", {1, 11}},
        {"long-line", std::string(1 << 20, 'x') + "\nend\n", {2, 1 << 20}},
        {"non-ascii", "naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n", {3, 10}},
    };
    for (const auto& c : cases) {
        write_file(c.data);
        auto got = line_stats(input);
        check(c.name, got.has_value() && *got == c.want);
    }

    const std::vector<std::pair<std::string, std::string>> invalid = {
        {"invalid-byte", "ok\n\xff\xfe\n"s},
        {"truncated-at-end", "ok\ncaf\xc3"s},
        {"encoded-surrogate", "a\xed\xa0\x80"s + "b\n"},
        {"overlong", "\xc0\xaf\n"s},
    };
    for (const auto& [name, data] : invalid) {
        write_file(data);
        auto got = line_stats(input);
        check(name, !got && got.error() == ReadError::invalid_utf8);
    }

    auto missing = line_stats("missing.txt");
    check("missing", !missing && missing.error() == ReadError::cannot_open);

    std::filesystem::remove(input);
    if (failures > 0) return EXIT_FAILURE;
    std::puts("all tests passed");
}
LineStats.javaI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.IntSummaryStatistics;
import java.util.stream.Stream;

/** The number of lines of a text file and the number of code points in its longest line. */
public record LineStats(long lines, long longest) {

  /**
   * Reads a UTF-8 text file line by line.
   *
   * @throws java.nio.file.NoSuchFileException if the file does not exist
   * @throws java.nio.charset.MalformedInputException if the bytes are not valid UTF-8
   */
  public static LineStats of(Path path) throws IOException {
    // Files.lines decodes UTF-8 and reads lazily. Close the stream to close the file.
    try (Stream<String> lines = Files.lines(path)) {
      IntSummaryStatistics stats =
          lines.mapToInt(line -> line.codePointCount(0, line.length())).summaryStatistics();
      return new LineStats(stats.getCount(), Math.max(0, stats.getMax()));
    } catch (UncheckedIOException e) {
      // The stream wraps an error of a later read, such as a bad byte sequence.
      throw e.getCause();
    }
  }
}
LineStatsTest.java 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class LineStatsTest {
  @TempDir Path dir;

  private Path write(byte[] data) throws IOException {
    return Files.write(dir.resolve("input.txt"), data);
  }

  private static Arguments text(String name, String data, long lines, long longest) {
    return Arguments.of(name, data.getBytes(StandardCharsets.UTF_8), lines, longest);
  }

  static Stream<Arguments> cases() {
    return Stream.of(
        text("lf", "alpha\nbeta\ngamma\n", 3, 5),
        text("blank-lines", "first\n\n\nlast line\n", 4, 9),
        text("empty", "", 0, 0),
        text("only-newline", "\n", 1, 0),
        text("no-final-newline", "one\ntwo\nthree", 3, 5),
        text("crlf", "one\r\ntwo\r\nthree\r\n", 3, 5),
        text("crlf-no-final-newline", "one\r\ntwo\r\nthree", 3, 5),
        text("mixed-endings", "one\r\ntwo\nthree\r\n", 3, 5),
        text("whitespace", "  two spaces\ttab \n", 1, 17),
        text("backslashes", "C:\\temp\\new\n", 1, 11),
        text("long-line", "x".repeat(1 << 20) + "\nend\n", 2, 1 << 20),
        text("non-ascii", "naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n", 3, 10));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void lineStats(String name, byte[] data, long lines, long longest) throws IOException {
    assertEquals(new LineStats(lines, longest), LineStats.of(write(data)));
  }

  @Test
  void missingFile() {
    assertThrows(NoSuchFileException.class, () -> LineStats.of(dir.resolve("missing.txt")));
  }

  static Stream<Arguments> invalid() {
    return Stream.of(
        Arguments.of("invalid-byte", new byte[] {'o', 'k', '\n', (byte) 0xff, (byte) 0xfe, '\n'}),
        Arguments.of("truncated-at-end", new byte[] {'o', 'k', '\n', 'c', 'a', 'f', (byte) 0xc3}),
        Arguments.of(
            "encoded-surrogate", new byte[] {'a', (byte) 0xed, (byte) 0xa0, (byte) 0x80, 'b', '\n'}),
        Arguments.of("overlong", new byte[] {(byte) 0xc0, (byte) 0xaf, '\n'}));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("invalid")
  void invalidUtf8(String name, byte[] data) throws IOException {
    Path path = write(data);
    assertThrows(MalformedInputException.class, () -> LineStats.of(path));
  }
}
line_stats.cI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

// getline is in POSIX.1-2008, not in ISO C.
#define _POSIX_C_SOURCE 200809L

#include "line_stats.h"

#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

// utf8_count checks that s[0..n) is valid UTF-8 (RFC 3629) and stores the
// number of code points in *count. It rejects overlong forms, surrogates and
// values above U+10FFFF.
static bool utf8_count(const unsigned char *s, size_t n, size_t *count) {
    size_t k = 0;
    for (size_t i = 0; i < n; k++) {
        unsigned char c = s[i];
        size_t len;
        unsigned char lo = 0x80, hi = 0xBF; // the range of the second byte
        if (c < 0x80) {
            i++;
            continue;
        } else if (c >= 0xC2 && c <= 0xDF) {
            len = 2;
        } else if (c >= 0xE0 && c <= 0xEF) {
            len = 3;
            if (c == 0xE0) lo = 0xA0; // no overlong form
            if (c == 0xED) hi = 0x9F; // no surrogate
        } else if (c >= 0xF0 && c <= 0xF4) {
            len = 4;
            if (c == 0xF0) lo = 0x90; // no overlong form
            if (c == 0xF4) hi = 0x8F; // no value above U+10FFFF
        } else {
            return false;
        }
        if (n - i < len || s[i + 1] < lo || s[i + 1] > hi) return false;
        for (size_t j = 2; j < len; j++) {
            if ((s[i + j] & 0xC0) != 0x80) return false;
        }
        i += len;
    }
    *count = k;
    return true;
}

int line_stats(const char *path, size_t *lines, size_t *longest) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) return -1;

    char *line = NULL;
    size_t cap = 0;
    size_t count = 0, max = 0;
    ssize_t len;
    int err = 0;
    // getline returns -1 at the end of the file and on an error.
    while ((len = getline(&line, &cap, f)) != -1) {
        if (len > 0 && line[len - 1] == '\n') len--;
        if (len > 0 && line[len - 1] == '\r') len--;
        size_t cps;
        if (!utf8_count((const unsigned char *)line, (size_t)len, &cps)) {
            err = EILSEQ;
            break;
        }
        count++;
        if (cps > max) max = cps;
    }
    if (err == 0 && ferror(f)) err = errno;
    free(line);
    fclose(f);
    if (err != 0) {
        errno = err;
        return -1;
    }
    *lines = count;
    *longest = max;
    return 0;
}
line_stats.h 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

#ifndef LINE_STATS_H
#define LINE_STATS_H

#include <stddef.h>

// line_stats reads the UTF-8 text file at path line by line. It stores the
// number of lines in *lines and the number of code points of the longest line
// in *longest, and returns 0. On an error it returns -1 and sets errno:
// EILSEQ for bytes that are not valid UTF-8, or the error of fopen or getline.
int line_stats(const char *path, size_t *lines, size_t *longest);

#endif
test_line_stats.c 80 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

#include "line_stats.h"

#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static const char *path = "line_stats_input.txt";

static void write_file(const char *data, size_t n) {
    FILE *f = fopen(path, "wb");
    assert(f != NULL);
    assert(fwrite(data, 1, n, f) == n);
    assert(fclose(f) == 0);
}

#define CASE(name, data, want_lines, want_longest) \
    check(name, data, sizeof(data) - 1, want_lines, want_longest)

static void check(const char *name, const char *data, size_t n,
                  size_t want_lines, size_t want_longest) {
    write_file(data, n);
    size_t lines = 99, longest = 99;
    if (line_stats(path, &lines, &longest) != 0 || lines != want_lines ||
        longest != want_longest) {
        fprintf(stderr, "case %s: got %zu, %zu\n", name, lines, longest);
        exit(1);
    }
}

static void check_invalid(const char *name, const char *data, size_t n) {
    write_file(data, n);
    size_t lines, longest;
    errno = 0;
    if (line_stats(path, &lines, &longest) != -1 || errno != EILSEQ) {
        fprintf(stderr, "case %s: no EILSEQ error\n", name);
        exit(1);
    }
}

#define INVALID(name, data) check_invalid(name, data, sizeof(data) - 1)

int main(void) {
    CASE("lf", "alpha\nbeta\ngamma\n", 3, 5);
    CASE("blank-lines", "first\n\n\nlast line\n", 4, 9);
    CASE("empty", "", 0, 0);
    CASE("only-newline", "\n", 1, 0);
    CASE("no-final-newline", "one\ntwo\nthree", 3, 5);
    CASE("crlf", "one\r\ntwo\r\nthree\r\n", 3, 5);
    CASE("crlf-no-final-newline", "one\r\ntwo\r\nthree", 3, 5);
    CASE("mixed-endings", "one\r\ntwo\nthree\r\n", 3, 5);
    CASE("whitespace", "  two spaces\ttab \n", 1, 17);
    CASE("backslashes", "C:\\temp\\new\n", 1, 11);
    CASE("non-ascii", "naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n", 3, 10);

    size_t n = (size_t)1 << 20;
    char *long_line = malloc(n + 5);
    assert(long_line != NULL);
    memset(long_line, 'x', n);
    memcpy(long_line + n, "\nend\n", 5);
    check("long-line", long_line, n + 5, 2, n);
    free(long_line);

    INVALID("invalid-byte", "ok\n\xff\xfe\n");
    INVALID("truncated-at-end", "ok\ncaf\xc3");
    INVALID("encoded-surrogate", "a\xed\xa0\x80" "b\n");
    INVALID("overlong", "\xc0\xaf\n");

    size_t lines, longest;
    errno = 0;
    assert(line_stats("missing.txt", &lines, &longest) == -1 && errno == ENOENT);

    remove(path);
    puts("all tests passed");
    return 0;
}
LineStats.csI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

using System.Text;

/// <summary>The number of lines of a text file and the number of code points in its longest line.</summary>
public readonly record struct LineStats(long Lines, long Longest)
{
    // throwOnInvalidBytes: true makes the decoder throw on a bad byte sequence.
    // The default UTF-8 decoder puts U+FFFD in its place and does not tell you.
    private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);

    /// <summary>Reads a UTF-8 text file line by line.</summary>
    /// <exception cref="FileNotFoundException">The file does not exist.</exception>
    /// <exception cref="DecoderFallbackException">The bytes are not valid UTF-8.</exception>
    public static LineStats Read(string path)
    {
        long lines = 0, longest = 0;
        foreach (string line in File.ReadLines(path, StrictUtf8))
        {
            lines++;
            longest = Math.Max(longest, line.EnumerateRunes().Count());
        }
        return new LineStats(lines, longest);
    }
}
LineStatsTests.cs 58 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

using System.Text;
using Xunit;

public sealed class LineStatsTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("line-stats-").FullName;

    public void Dispose() => Directory.Delete(dir, recursive: true);

    private string Write(byte[] data)
    {
        string path = Path.Combine(dir, "input.txt");
        File.WriteAllBytes(path, data);
        return path;
    }

    public static TheoryData<string, string, long, long> Cases => new()
    {
        { "lf", "alpha\nbeta\ngamma\n", 3, 5 },
        { "blank-lines", "first\n\n\nlast line\n", 4, 9 },
        { "empty", "", 0, 0 },
        { "only-newline", "\n", 1, 0 },
        { "no-final-newline", "one\ntwo\nthree", 3, 5 },
        { "crlf", "one\r\ntwo\r\nthree\r\n", 3, 5 },
        { "crlf-no-final-newline", "one\r\ntwo\r\nthree", 3, 5 },
        { "mixed-endings", "one\r\ntwo\nthree\r\n", 3, 5 },
        { "whitespace", "  two spaces\ttab \n", 1, 17 },
        { "backslashes", "C:\\temp\\new\n", 1, 11 },
        { "long-line", new string('x', 1 << 20) + "\nend\n", 2, 1 << 20 },
        { "non-ascii", "naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n", 3, 10 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void CountsLines(string name, string text, long lines, long longest)
    {
        Assert.False(string.IsNullOrEmpty(name));
        Assert.Equal(new LineStats(lines, longest), LineStats.Read(Write(Encoding.UTF8.GetBytes(text))));
    }

    [Fact]
    public void MissingFile() =>
        Assert.Throws<FileNotFoundException>(() => LineStats.Read(Path.Combine(dir, "missing.txt")));

    [Theory]
    [InlineData("invalid-byte", new byte[] { 0x6f, 0x6b, 0x0a, 0xff, 0xfe, 0x0a })]
    [InlineData("truncated-at-end", new byte[] { 0x6f, 0x6b, 0x0a, 0x63, 0x61, 0x66, 0xc3 })]
    [InlineData("encoded-surrogate", new byte[] { 0x61, 0xed, 0xa0, 0x80, 0x62, 0x0a })]
    [InlineData("overlong", new byte[] { 0xc0, 0xaf, 0x0a })]
    public void InvalidUtf8(string name, byte[] data)
    {
        Assert.False(string.IsNullOrEmpty(name));
        Assert.Throws<DecoderFallbackException>(() => LineStats.Read(Write(data)));
    }
}
lineStats.jsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";
import { Readable } from "node:stream";

// Decodes chunks of bytes as UTF-8. A bad byte sequence throws a TypeError.
// readline alone would replace it with U+FFFD and go on.
async function* decodeUtf8(chunks) {
  const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
  for await (const chunk of chunks) {
    yield decoder.decode(chunk, { stream: true });
  }
  yield decoder.decode(); // throws if the file ends inside a sequence
}

// A string holds UTF-16 code units; the iterator of a string gives code points.
function codePoints(text) {
  let count = 0;
  for (const _ of text) count++;
  return count;
}

/**
 * Returns the number of lines of a UTF-8 text file and the number of code
 * points in its longest line.
 * @param {string} path
 * @returns {Promise<{lines: number, longest: number}>}
 */
export async function lineStats(path) {
  const input = Readable.from(decodeUtf8(createReadStream(path)));
  // crlfDelay: Infinity makes "\r\n" one line break even when a chunk ends between "\r" and "\n".
  const reader = createInterface({ input, crlfDelay: Infinity });
  let lines = 0;
  let longest = 0;
  for await (const line of reader) {
    lines++;
    longest = Math.max(longest, codePoints(line));
  }
  return { lines, longest };
}
lineStats.test.js 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

import assert from "node:assert/strict";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";

import { lineStats } from "./lineStats.js";

const dir = mkdtempSync(join(tmpdir(), "line-stats-"));

function write(name, data) {
  const path = join(dir, name);
  writeFileSync(path, data);
  return path;
}

const cases = [
  ["lf", "alpha\nbeta\ngamma\n", 3, 5],
  ["blank-lines", "first\n\n\nlast line\n", 4, 9],
  ["empty", "", 0, 0],
  ["only-newline", "\n", 1, 0],
  ["no-final-newline", "one\ntwo\nthree", 3, 5],
  ["crlf", "one\r\ntwo\r\nthree\r\n", 3, 5],
  ["crlf-no-final-newline", "one\r\ntwo\r\nthree", 3, 5],
  ["mixed-endings", "one\r\ntwo\nthree\r\n", 3, 5],
  ["whitespace", "  two spaces\ttab \n", 1, 17],
  ["backslashes", "C:\\temp\\new\n", 1, 11],
  ["long-line", "x".repeat(1 << 20) + "\nend\n", 2, 1 << 20],
  ["non-ascii", "naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n", 3, 10],
];

for (const [name, data, lines, longest] of cases) {
  test(name, async () => {
    assert.deepEqual(await lineStats(write(name, data)), { lines, longest });
  });
}

test("missing", async () => {
  await assert.rejects(lineStats(join(dir, "missing.txt")), { code: "ENOENT" });
});

const invalid = [
  ["invalid-byte", [0x6f, 0x6b, 0x0a, 0xff, 0xfe, 0x0a]],
  ["truncated-at-end", [0x6f, 0x6b, 0x0a, 0x63, 0x61, 0x66, 0xc3]],
  ["encoded-surrogate", [0x61, 0xed, 0xa0, 0x80, 0x62, 0x0a]],
  ["overlong", [0xc0, 0xaf, 0x0a]],
];

for (const [name, bytes] of invalid) {
  test(name, async () => {
    const path = write(name, Uint8Array.from(bytes));
    await assert.rejects(lineStats(path), { code: "ERR_ENCODING_INVALID_ENCODED_DATA" });
  });
}
lineStats.tsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";
import { Readable } from "node:stream";

export interface LineStats {
  lines: number;
  longest: number; // in code points
}

// Decodes chunks of bytes as UTF-8. A bad byte sequence throws a TypeError.
// readline alone would replace it with U+FFFD and go on.
async function* decodeUtf8(chunks: AsyncIterable<Uint8Array>): AsyncGenerator<string> {
  const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
  for await (const chunk of chunks) {
    yield decoder.decode(chunk, { stream: true });
  }
  yield decoder.decode(); // throws if the file ends inside a sequence
}

// A string holds UTF-16 code units; the iterator of a string gives code points.
function codePoints(text: string): number {
  let count = 0;
  for (const _ of text) count++;
  return count;
}

export async function lineStats(path: string): Promise<LineStats> {
  const input = Readable.from(decodeUtf8(createReadStream(path)));
  // crlfDelay: Infinity makes "\r\n" one line break even when a chunk ends between "\r" and "\n".
  const reader = createInterface({ input, crlfDelay: Infinity });
  let lines = 0;
  let longest = 0;
  for await (const line of reader) {
    lines++;
    longest = Math.max(longest, codePoints(line));
  }
  return { lines, longest };
}
lineStats.test.ts 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

import assert from "node:assert/strict";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";

import { lineStats } from "./lineStats.ts";

const dir = mkdtempSync(join(tmpdir(), "line-stats-"));

function write(name: string, data: string | Uint8Array): string {
  const path = join(dir, name);
  writeFileSync(path, data);
  return path;
}

const cases: [string, string, number, number][] = [
  ["lf", "alpha\nbeta\ngamma\n", 3, 5],
  ["blank-lines", "first\n\n\nlast line\n", 4, 9],
  ["empty", "", 0, 0],
  ["only-newline", "\n", 1, 0],
  ["no-final-newline", "one\ntwo\nthree", 3, 5],
  ["crlf", "one\r\ntwo\r\nthree\r\n", 3, 5],
  ["crlf-no-final-newline", "one\r\ntwo\r\nthree", 3, 5],
  ["mixed-endings", "one\r\ntwo\nthree\r\n", 3, 5],
  ["whitespace", "  two spaces\ttab \n", 1, 17],
  ["backslashes", "C:\\temp\\new\n", 1, 11],
  ["long-line", "x".repeat(1 << 20) + "\nend\n", 2, 1 << 20],
  ["non-ascii", "naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n", 3, 10],
];

for (const [name, data, lines, longest] of cases) {
  test(name, async () => {
    assert.deepEqual(await lineStats(write(name, data)), { lines, longest });
  });
}

test("missing", async () => {
  await assert.rejects(lineStats(join(dir, "missing.txt")), { code: "ENOENT" });
});

const invalid: [string, number[]][] = [
  ["invalid-byte", [0x6f, 0x6b, 0x0a, 0xff, 0xfe, 0x0a]],
  ["truncated-at-end", [0x6f, 0x6b, 0x0a, 0x63, 0x61, 0x66, 0xc3]],
  ["encoded-surrogate", [0x61, 0xed, 0xa0, 0x80, 0x62, 0x0a]],
  ["overlong", [0xc0, 0xaf, 0x0a]],
];

for (const [name, bytes] of invalid) {
  test(name, async () => {
    const path = write(name, Uint8Array.from(bytes));
    await assert.rejects(lineStats(path), { code: "ERR_ENCODING_INVALID_ENCODED_DATA" });
  });
}
line_stats.goI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

// Package linestats reads a text file line by line.
package linestats

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"unicode/utf8"
)

// MaxLine is the longest line, in bytes, that LineStats accepts. The default limit of bufio.Scanner is 64 KiB.
const MaxLine = 64 << 20

// ErrInvalidUTF8 reports a line that is not valid UTF-8.
var ErrInvalidUTF8 = errors.New("invalid UTF-8")

// LineStats returns the number of lines of a UTF-8 text file and the number of code points in its longest line.
func LineStats(path string) (lines, longest int, err error) {
	f, err := os.Open(path)
	if err != nil {
		return 0, 0, err
	}
	defer f.Close()

	s := bufio.NewScanner(f)
	s.Buffer(make([]byte, 0, 64*1024), MaxLine)
	for s.Scan() {
		line := s.Bytes() // without "\n" or "\r\n"; valid until the next Scan
		lines++
		if !utf8.Valid(line) {
			return 0, 0, fmt.Errorf("%s: line %d: %w", path, lines, ErrInvalidUTF8)
		}
		longest = max(longest, utf8.RuneCount(line))
	}
	if err := s.Err(); err != nil {
		return 0, 0, fmt.Errorf("%s: line %d: %w", path, lines+1, err)
	}
	return lines, longest, nil
}
line_stats_test.go 81 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

package linestats

import (
	"bufio"
	"errors"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func write(t *testing.T, data string) string {
	t.Helper()
	path := filepath.Join(t.TempDir(), "input.txt")
	if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
		t.Fatal(err)
	}
	return path
}

func TestCases(t *testing.T) {
	cases := []struct {
		name           string
		data           string
		lines, longest int
	}{
		{"lf", "alpha\nbeta\ngamma\n", 3, 5},
		{"blank-lines", "first\n\n\nlast line\n", 4, 9},
		{"empty", "", 0, 0},
		{"only-newline", "\n", 1, 0},
		{"no-final-newline", "one\ntwo\nthree", 3, 5},
		{"crlf", "one\r\ntwo\r\nthree\r\n", 3, 5},
		{"crlf-no-final-newline", "one\r\ntwo\r\nthree", 3, 5},
		{"mixed-endings", "one\r\ntwo\nthree\r\n", 3, 5},
		{"whitespace", "  two spaces\ttab \n", 1, 17},
		{"backslashes", `C:\temp\new` + "\n", 1, 11},
		{"long-line", strings.Repeat("x", 1<<20) + "\nend\n", 2, 1 << 20},
		{"non-ascii", "naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n", 3, 10},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			lines, longest, err := LineStats(write(t, c.data))
			if err != nil || lines != c.lines || longest != c.longest {
				t.Errorf("LineStats = %d, %d, %v; want %d, %d, nil", lines, longest, err, c.lines, c.longest)
			}
		})
	}
}

func TestMissingFile(t *testing.T) {
	_, _, err := LineStats(filepath.Join(t.TempDir(), "missing.txt"))
	if !errors.Is(err, fs.ErrNotExist) {
		t.Errorf("err = %v, want fs.ErrNotExist", err)
	}
}

func TestInvalidUTF8(t *testing.T) {
	for name, data := range map[string]string{
		"invalid-byte":      "ok\n\xff\xfe\n",
		"truncated-at-end":  "ok\ncaf\xc3",
		"encoded-surrogate": "a\xed\xa0\x80b\n",
		"overlong":          "\xc0\xaf\n",
	} {
		t.Run(name, func(t *testing.T) {
			if _, _, err := LineStats(write(t, data)); !errors.Is(err, ErrInvalidUTF8) {
				t.Errorf("err = %v, want ErrInvalidUTF8", err)
			}
		})
	}
}

// The default buffer of bufio.Scanner stops at a line of 64 KiB. LineStats raises the limit, and a longer line is still an error.
func TestLineTooLong(t *testing.T) {
	if _, _, err := LineStats(write(t, strings.Repeat("x", MaxLine+1))); !errors.Is(err, bufio.ErrTooLong) {
		t.Errorf("err = %v, want bufio.ErrTooLong", err)
	}
}
line_stats.rsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

//! Read a text file line by line.

use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::Path;

/// Returns the number of lines of a UTF-8 text file and the number of code points in its longest line.
///
/// A line that is not valid UTF-8 gives an error of kind `InvalidData`.
pub fn line_stats(path: impl AsRef<Path>) -> io::Result<(usize, usize)> {
    let reader = BufReader::new(File::open(path)?);
    let mut lines = 0;
    let mut longest = 0;
    // Each line comes without its "\n" or "\r\n".
    for line in reader.lines() {
        let line = line?;
        lines += 1;
        longest = longest.max(line.chars().count());
    }
    Ok((lines, longest))
}
tests/line_stats_test.rs 64 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;

use algo_read_a_file_line_by_line::line_stats;

/// Writes the bytes to a new file in the temporary directory and returns its path.
fn write(name: &str, data: &[u8]) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("line-stats-{}", std::process::id()));
    fs::create_dir_all(&dir).unwrap();
    let path = dir.join(name);
    fs::write(&path, data).unwrap();
    path
}

#[test]
fn cases() {
    let long = [&b"x".repeat(1 << 20)[..], b"\nend\n"].concat();
    let cases: [(&str, &[u8], (usize, usize)); 12] = [
        ("lf", b"alpha\nbeta\ngamma\n", (3, 5)),
        ("blank-lines", b"first\n\n\nlast line\n", (4, 9)),
        ("empty", b"", (0, 0)),
        ("only-newline", b"\n", (1, 0)),
        ("no-final-newline", b"one\ntwo\nthree", (3, 5)),
        ("crlf", b"one\r\ntwo\r\nthree\r\n", (3, 5)),
        ("crlf-no-final-newline", b"one\r\ntwo\r\nthree", (3, 5)),
        ("mixed-endings", b"one\r\ntwo\nthree\r\n", (3, 5)),
        ("whitespace", b"  two spaces\ttab \n", (1, 17)),
        ("backslashes", b"C:\\temp\\new\n", (1, 11)),
        ("long-line", &long, (2, 1 << 20)),
        (
            "non-ascii",
            "naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n".as_bytes(),
            (3, 10),
        ),
    ];
    for (name, data, want) in cases {
        let got = line_stats(write(name, data)).unwrap();
        assert_eq!(got, want, "case {name}");
    }
}

#[test]
fn missing_file() {
    let err = line_stats(write("present", b"").with_file_name("missing")).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
}

#[test]
fn invalid_utf8() {
    let cases: [(&str, &[u8]); 4] = [
        ("invalid-byte", b"ok\n\xff\xfe\n"),
        ("truncated-at-end", b"ok\ncaf\xc3"),
        ("encoded-surrogate", b"a\xed\xa0\x80b\n"),
        ("overlong", b"\xc0\xaf\n"),
    ];
    for (name, data) in cases {
        let err = line_stats(write(name, data)).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidData, "case {name}");
    }
}
LineStats.ktI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

import java.nio.file.Path
import kotlin.io.path.useLines

/** The number of lines of a text file and the number of code points in its longest line. */
data class LineStats(val lines: Long, val longest: Long)

/**
 * Reads a UTF-8 text file line by line.
 *
 * Throws [java.nio.file.NoSuchFileException] if the file does not exist, and
 * [java.nio.charset.MalformedInputException] if the bytes are not valid UTF-8.
 */
fun lineStats(path: Path): LineStats =
    // Path.useLines reads with Files.newBufferedReader, which reports a bad byte sequence.
    path.useLines { lines ->
        var count = 0L
        var longest = 0L
        for (line in lines) {
            count++
            longest = maxOf(longest, line.codePointCount(0, line.length).toLong())
        }
        LineStats(count, longest)
    }
LineStatsTest.kt 61 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-file-line-by-line/.

import java.nio.charset.MalformedInputException
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import kotlin.io.path.writeBytes
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.io.TempDir

class LineStatsTest {
    @TempDir lateinit var dir: Path

    private fun write(data: ByteArray): Path = dir.resolve("input.txt").also { it.writeBytes(data) }

    private fun bytes(vararg b: Int) = ByteArray(b.size) { b[it].toByte() }

    @Test
    fun cases() {
        val cases =
            listOf(
                Triple("lf", "alpha\nbeta\ngamma\n", LineStats(3, 5)),
                Triple("blank-lines", "first\n\n\nlast line\n", LineStats(4, 9)),
                Triple("empty", "", LineStats(0, 0)),
                Triple("only-newline", "\n", LineStats(1, 0)),
                Triple("no-final-newline", "one\ntwo\nthree", LineStats(3, 5)),
                Triple("crlf", "one\r\ntwo\r\nthree\r\n", LineStats(3, 5)),
                Triple("crlf-no-final-newline", "one\r\ntwo\r\nthree", LineStats(3, 5)),
                Triple("mixed-endings", "one\r\ntwo\nthree\r\n", LineStats(3, 5)),
                Triple("whitespace", "  two spaces\ttab \n", LineStats(1, 17)),
                Triple("backslashes", "C:\\temp\\new\n", LineStats(1, 11)),
                Triple("long-line", "x".repeat(1 shl 20) + "\nend\n", LineStats(2, 1L shl 20)),
                Triple("non-ascii", "naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n", LineStats(3, 10)),
            )
        for ((name, data, want) in cases) {
            assertEquals(want, lineStats(write(data.toByteArray())), name)
        }
    }

    @Test
    fun missingFile() {
        assertThrows<NoSuchFileException> { lineStats(dir.resolve("missing.txt")) }
    }

    @Test
    fun invalidUtf8() {
        val cases =
            mapOf(
                "invalid-byte" to bytes(0x6f, 0x6b, 0x0a, 0xff, 0xfe, 0x0a),
                "truncated-at-end" to bytes(0x6f, 0x6b, 0x0a, 0x63, 0x61, 0x66, 0xc3),
                "encoded-surrogate" to bytes(0x61, 0xed, 0xa0, 0x80, 0x62, 0x0a),
                "overlong" to bytes(0xc0, 0xaf, 0x0a),
            )
        for ((name, data) in cases) {
            val path = write(data)
            assertThrows<MalformedInputException>(name) { lineStats(path) }
        }
    }
}
line_stats.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-file-line-by-line/.
# Needs Bash 4.4 or later, for "wait" on a process substitution.

# line_stats PATH
# Prints "LINES LONGEST": the number of lines, and the characters in the longest line.
# Returns a nonzero status, and prints nothing on stdout, if the file is missing or not valid UTF-8.
line_stats() {
  local LC_ALL=C.UTF-8 # ${#line} counts characters only in a UTF-8 locale.
  local line lines=0 longest=0
  # IFS= keeps leading and trailing blanks. -r keeps backslashes.
  # read fails on a last line with no newline, but it still sets $line.
  while IFS= read -r line || [[ -n $line ]]; do
    # ${line%$'\r'} also works, but it takes quadratic time on a long line.
    if [[ $line == *$'\r' ]]; then
      line=${line:0:-1}
    fi
    lines=$((lines + 1))
    if ((${#line} > longest)); then
      longest=${#line}
    fi
  done < <(iconv -f UTF-8 -t UTF-8 -- "$1")
  # iconv stops with an error on a bad byte sequence or a missing file.
  wait "$!" || return
  printf '%d %d\n' "$lines" "$longest"
}
test_line_stats.bats 54 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-file-line-by-line/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/line_stats.sh"
  file="$BATS_TEST_TMPDIR/input.txt"
}

check() { # check BYTES WANT
  printf '%b' "$1" >"$file"
  run line_stats "$file"
  [ "$status" -eq 0 ]
  [ "$output" = "$2" ]
}

@test "lf" { check 'alpha\nbeta\ngamma\n' "3 5"; }
@test "blank-lines" { check 'first\n\n\nlast line\n' "4 9"; }
@test "empty" { check '' "0 0"; }
@test "only-newline" { check '\n' "1 0"; }
@test "no-final-newline" { check 'one\ntwo\nthree' "3 5"; }
@test "crlf" { check 'one\r\ntwo\r\nthree\r\n' "3 5"; }
@test "crlf-no-final-newline" { check 'one\r\ntwo\r\nthree' "3 5"; }
@test "mixed-endings" { check 'one\r\ntwo\nthree\r\n' "3 5"; }
@test "whitespace" { check '  two spaces\ttab \n' "1 17"; }
@test "backslashes" { check 'C:\\temp\\new\n' "1 11"; }
@test "non-ascii" { check 'naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n' "3 10"; }

@test "long-line" {
  { head -c 1048576 /dev/zero | tr '\0' x; printf '\nend\n'; } >"$file"
  run line_stats "$file"
  [ "$status" -eq 0 ]
  [ "$output" = "2 1048576" ]
}

@test "missing" {
  run --separate-stderr line_stats "$BATS_TEST_TMPDIR/missing.txt"
  [ "$status" -ne 0 ]
  [ -z "$output" ]
}

invalid() { # invalid BYTES
  printf '%b' "$1" >"$file"
  run --separate-stderr line_stats "$file"
  [ "$status" -ne 0 ]
  [ -z "$output" ]
}

@test "invalid-byte" { invalid 'ok\n\xff\xfe\n'; }
@test "truncated-at-end" { invalid 'ok\ncaf\xc3'; }
@test "encoded-surrogate" { invalid 'a\xed\xa0\x80b\n'; }
@test "overlong" { invalid '\xc0\xaf\n'; }
Get-LineStats.ps1I0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-file-line-by-line/.

function Get-LineStats {
    <#
    .SYNOPSIS
    Reads a UTF-8 text file line by line.
    .OUTPUTS
    An object with Lines, the number of lines, and Longest, the code points in the longest line.
    Throws if the file does not exist or the bytes are not valid UTF-8.
    #>
    [CmdletBinding()]
    param([Parameter(Mandatory)][string] $Path)

    # .NET resolves a relative path from the process directory, not from $PWD.
    $full = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path)
    # Get-Content puts U+FFFD in place of a bad byte sequence. This decoder throws.
    $strict = [System.Text.UTF8Encoding]::new($false, $true)
    $lines = 0L
    $longest = 0L
    try {
        # ReadLines opens the file now, but reads it only as foreach asks for lines.
        $reader = [System.IO.File]::ReadLines($full, $strict)
    } catch [System.Management.Automation.MethodInvocationException] {
        # Throw the FileNotFoundException itself, not the wrapper of the method call.
        throw $_.Exception.InnerException
    }
    foreach ($line in $reader) {
        $lines++
        $length = [System.Linq.Enumerable]::Count($line.EnumerateRunes())
        if ($length -gt $longest) { $longest = $length }
    }
    [pscustomobject]@{ Lines = $lines; Longest = $longest }
}
Get-LineStats.Tests.ps1 50 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-file-line-by-line/.

BeforeAll {
    . (Join-Path $PSScriptRoot 'Get-LineStats.ps1')
    $script:file = Join-Path $TestDrive 'input.txt'
}

Describe 'Get-LineStats' {
    It '<Name>' -ForEach @(
        @{ Name = 'lf'; Text = "alpha`nbeta`ngamma`n"; Lines = 3; Longest = 5 }
        @{ Name = 'blank-lines'; Text = "first`n`n`nlast line`n"; Lines = 4; Longest = 9 }
        @{ Name = 'empty'; Text = ''; Lines = 0; Longest = 0 }
        @{ Name = 'only-newline'; Text = "`n"; Lines = 1; Longest = 0 }
        @{ Name = 'no-final-newline'; Text = "one`ntwo`nthree"; Lines = 3; Longest = 5 }
        @{ Name = 'crlf'; Text = "one`r`ntwo`r`nthree`r`n"; Lines = 3; Longest = 5 }
        @{ Name = 'crlf-no-final-newline'; Text = "one`r`ntwo`r`nthree"; Lines = 3; Longest = 5 }
        @{ Name = 'mixed-endings'; Text = "one`r`ntwo`nthree`r`n"; Lines = 3; Longest = 5 }
        @{ Name = 'whitespace'; Text = "  two spaces`ttab `n"; Lines = 1; Longest = 17 }
        @{ Name = 'backslashes'; Text = "C:\temp\new`n"; Lines = 1; Longest = 11 }
        @{ Name = 'long-line'; Text = ('x' * 1MB) + "`nend`n"; Lines = 2; Longest = 1MB }
        @{ Name = 'non-ascii'; Text = "na`u{EF}ve caf`u{E9}`n`u{65E5}`u{672C}`u{8A9E}`u{306E}`u{30C6}`u{30AD}`u{30B9}`u{30C8}`n" + ("`u{1F642}" * 6) + "`n"; Lines = 3; Longest = 10 }
    ) {
        [System.IO.File]::WriteAllBytes($file, [System.Text.UTF8Encoding]::new($false).GetBytes($Text))
        $result = Get-LineStats -Path $file
        $result.Lines | Should -Be $Lines
        $result.Longest | Should -Be $Longest
    }

    It 'missing' {
        { Get-LineStats -Path (Join-Path $TestDrive 'missing.txt') } |
            Should -Throw -ExceptionType ([System.IO.FileNotFoundException])
    }

    It '<Name>' -ForEach @(
        @{ Name = 'invalid-byte'; Bytes = [byte[]](0x6f, 0x6b, 0x0a, 0xff, 0xfe, 0x0a) }
        @{ Name = 'truncated-at-end'; Bytes = [byte[]](0x6f, 0x6b, 0x0a, 0x63, 0x61, 0x66, 0xc3) }
        @{ Name = 'encoded-surrogate'; Bytes = [byte[]](0x61, 0xed, 0xa0, 0x80, 0x62, 0x0a) }
        @{ Name = 'overlong'; Bytes = [byte[]](0xc0, 0xaf, 0x0a) }
    ) {
        [System.IO.File]::WriteAllBytes($file, $Bytes)
        { Get-LineStats -Path $file } | Should -Throw -ExceptionType ([System.Text.DecoderFallbackException])
    }

    It 'resolves a relative path from the current location' {
        [System.IO.File]::WriteAllBytes($file, [byte[]](0x61, 0x0a))
        Push-Location $TestDrive
        try { (Get-LineStats -Path 'input.txt').Lines | Should -Be 1 } finally { Pop-Location }
    }
}

References

  1. The Open Group, POSIX.1-2024, Base Definitions, Chapter 3, Definitions, 3.185 Line, 3.172 Incomplete Line
  2. F. Yergeau, RFC 3629, UTF-8, a transformation format of ISO 10646 (2003), Section 3 and Section 10
  3. The Python Standard Library, Built-in Functions, open(), the encoding, errors and newline parameters
  4. The Python Tutorial, Input and Output, 7.2.1 Methods of File Objects
  5. PEP 686, Make UTF-8 mode default
  6. Node.js documentation, Readline, Example, read file stream line-by-line; the crlfDelay option of createInterface
  7. Node.js documentation, Util, class TextDecoder, the fatal option; the stream option of decode
  8. Java SE 25 API, java.nio.file.Files, lines(Path, Charset), lines(Path), readAllLines(Path, Charset)
  9. Kotlin standard library, kotlin.io.path, useLines
  10. .NET API reference, File.ReadLines, Remarks
  11. .NET API reference, UTF8Encoding constructors, UTF8Encoding(Boolean, Boolean), Remarks
  12. Go standard library, package bufio, MaxScanTokenSize, Scanner, Scanner.Buffer, Scanner.Err, ScanLines
  13. The Rust Standard Library, std::io::BufRead, lines, read_line (Errors)
  14. The Open Group, POSIX.1-2024, getdelim and getline, Return Value
  15. cppreference.com, std::getline
  16. Steve Summit, comp.lang.c FAQ list, Question 12.2
  17. GNU Bash Reference Manual, Bash Builtin Commands, read; wait
  18. GNU Bash, NEWS, new features in bash-4.4, item u
  19. PowerShell 7.6 reference, Get-Content, -Encoding, -ReadCount

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (cpp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (csharp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (go)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (java)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (javascript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (kotlin)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (powershell)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (rust)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (typescript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source

The native tests pass in 10 of 12 languages in this build.