Programming Search⌘K

Taskintro

Print the first and last lines of a file

Also called head and tail, first N lines of a file, last N lines of a file, head -n, tail -n.

Read a UTF-8 file one time and return its first N lines and its last N lines, as head -n and tail -n do, with a buffer that holds only N lines for the end.

Task

Read a text file and a count N, and return two lists: the first N lines of the file and the last N lines of the file. These are the jobs of head and tail. POSIX says that head "shall copy its input files to the standard output, ending the output for each file at a designated point",1 and that tail "shall copy its input file to the standard output beginning at a designated place".2 With -n N, head gives the first N lines and tail gives the last N lines.

The task needs rules for what a line is and for a file that is short. This page uses these rules:

  • A line ends at LF. POSIX defines a line as "A sequence of zero or more non- characters plus a terminating character."3 The LF is not part of the line in the result. A CR before the LF stays in the line.
  • A last line with no LF is a line too. POSIX calls it an incomplete line: "A sequence of one or more non- characters at the end of the file."3
  • A short file gives all its lines. For head, POSIX says: "When a file contains less than number bytes or lines, it shall be copied to standard output in its entirety. This shall not be an error."1 Here, if the file has fewer than N lines, each list has all the lines. So a line can be in the two lists.
  • N can be 0. Then the two lists are empty.
  • Each list keeps the order of the file. The last list starts with the line that is N lines before the end.

If the file does not exist, the solution reports an error.

Solutions

The first N lines are easy: read lines until there are N. The last N lines are more difficult, because the code does not know which lines are the last N until it gets to the end of the file. There are two methods:

  • Keep only N lines. Read the file one line at a time, and keep the last N lines in a queue. When the queue is full, remove the oldest line before you add the new one. At the end of the file, the queue holds the last N lines. The memory is for N lines, also for a very large file.
  • Read all the lines. Read the whole file, split it into lines, and take the lines from index max(len - N, 0) to the end. The code is short, but the memory is for the whole file.

The Python, Go, Rust and C++ solutions keep only N lines. The JavaScript, Java, C# and C solutions read all the lines. The Bash solution uses head and tail. POSIX lets tail keep the end of the file in memory too: "Tails relative to the end of the file may be saved in an internal buffer, and thus may be limited in length."2

  • Python. open(path, encoding='utf-8', newline='\n') opens the file as text. With a value such as '\n', "input lines are only terminated by the given string, and the line ending is returned to the caller untranslated",4 so a CR stays in the line. deque(maxlen=count) is the queue: "Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end."5 The documentation adds: "Bounded length deques provide functionality similar to the tail filter in Unix."5 A list holds the first lines while it has fewer than count.
  • JavaScript and TypeScript (Node.js). readFileSync(path, 'utf8') reads the file, and split('\n') gives the lines. If the last part is empty, the code removes it (see Pitfalls). slice(0, count) gives the first lines. For the last lines, the code computes start = Math.max(lines.length - count, 0) and calls slice(start). It does not use slice(-count): for a negative start, "start + array.length is used",6 but -0 is not negative, so slice(-0) is slice(0), which is all the lines. The TypeScript file adds types only.
  • Java. Files.readAllBytes(path) gives the bytes, and a loop splits them at each LF into an ArrayList. subList(0, take) and subList(size - take, size) select the two parts. subList "Returns a view of the portion of this list",7 not a copy, so List.copyOf copies each part. The result is a record Ends(first, last).
  • C#. File.ReadAllBytes(path) gives the bytes, Array.IndexOf finds each LF, and Encoding.UTF8.GetString decodes each line. GetRange(0, take) and GetRange(Count - take, take) select the two parts. The second argument of GetRange is "The number of elements in the range",8 not an end index. The result is a tuple (First, Last).
  • Go. bufio.Reader.ReadString('\n') reads each line: it "reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter."9 strings.TrimSuffix removes the LF. The queue is a ring: a slice of count strings, in which line number n goes to index n % count, over the line that came count lines before it. At the end, the code reads the ring from the oldest line to the newest.
  • Rust. BufReader::read_line reads each line, and pop removes the LF. The queue is a VecDeque, "A double-ended queue implemented with a growable ring buffer."10 When it has count lines, pop_front removes the oldest line, and then push_back adds the new line.
  • C. A loop of fread reads the file into a buffer that grows. fread "shall read into the array pointed to by ptr up to nitems elements",11 and the loop stops at the end of the file. The code changes each LF to a NUL, so each line is a C string, and it puts all the lines into one array. The two parts point into that array: the first part starts at index 0, and the last part starts at index n - take. first_and_last_lines fills a struct first_and_last, which the caller frees with first_and_last_free, or it returns -1 and sets errno.
  • C++. std::getline reads a binary std::ifstream one line at a time. The queue is a std::deque, which "allows fast insertion and deletion at both its beginning and its end."12 The result is a std::expected (C++23) that holds a pair of vectors, and the errors are cannot_open and read_failed.
  • Bash. head -n N -- FILE and tail -n N -- FILE do the work, and mapfile -t puts their output into two arrays. mapfile -t removes the LF at the end of each line, and keeps a CR. The function takes the names of the two arrays, and local -n refers to them, so it needs Bash 4.3 or later. If N is 0, the function does not run head (see Pitfalls).

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl, with one file for each in fixtures/.

  • two: N = 2 on a to e gives a, b and d, e.
  • one: N = 1 on first, middle, last gives first and last.
  • ten: N = 10 on the numbers 1 to 12 gives 1 to 10 and 3 to 12. The default of head is 10 lines: "If no options are specified, head shall act as if -n 10 had been specified."1
  • empty: an empty file gives two empty lists.
  • zero: N = 0 gives two empty lists.
  • short: N = 5 on two lines gives the two lines in each list.
  • exact: N = 2 on two lines gives the two lines in each list.
  • overlap: N = 2 on a, b, c gives a, b and b, c. The line b is in the two lists.
  • one-line: N = 1 on the one line a gives a in each list.
  • empty-lines and only-newline: an empty line at the start or the end is a line, so N = 1 gives an empty line in each list.
  • no-final-newline: N = 1 on a, b, c with no LF at the end gives a and c.
  • crlf: N = 1 on a CRLF, b CRLF gives a CR and b CR.
  • non-ascii: N = 1 on café, naïve, zoë gives café and zoë.

The tests also write a file of 100000 lines with the numbers 0 to 99999. N = 3 must give 0, 1, 2 and 99997, 99998, 99999. The case in cases/errors.jsonl must give the error not-found. The toolchain does not load that file yet, so each test file holds the case by name.

Pitfalls

  • tail -n +N counts from the start. The sign of the number tells tail where to start: a + is "Relative to the beginning of the file", and a - or no sign is "Relative to the end of the file".2 "The origin for counting shall be 1; that is, -n +1 represents the first line of the file, -n -1 the last."2 So tail -n +2 gives all the lines from line 2, not the last two lines:
f=$(mktemp)
printf 'a\nb\nc\nd\ne\n' >"$f"
echo "tail -n 2:"
tail -n 2 "$f"
echo "tail -n +2:"
tail -n +2 "$f"
rm "$f"
Output
tail -n 2:
d
e
tail -n +2:
b
c
d
e
  • head -n 0 can fail. POSIX says for head: "The application shall ensure that the number option-argument is a positive decimal integer."1 0 is not positive, so a version of head can refuse it. The Bash solution does not run head or tail when N is 0.
  • A negative index of 0 is not from the end. In Python, for a negative index, "len(s) + i or len(s) + j is substituted. But note that -0 is still 0".13 So lines[-count:] is correct for a count of 1 or more, but for a count of 0, it gives all the lines. lines[max(len(lines) - count, 0):] is correct for each count:
lines = ["a", "b", "c", "d"]
for count in [2, 1, 0]:
    print(count, lines[-count:], lines[max(len(lines) - count, 0):])
Output
2 ['c', 'd'] ['c', 'd']
1 ['d'] ['d']
0 ['a', 'b', 'c', 'd'] []
  • The LF at the end of the file makes an empty part. If the file ends with an LF, split('\n') gives an empty string after it. MDN says: "If separator appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e., zero length) string appearing at the first (or last) position of the returned array."14 So the last line seems to be empty. Remove the empty part before you take the last lines:
const text = "a\nb\n";
const parts = text.split("\n");
console.log(parts);
console.log(parts.slice(-1));
if (parts.at(-1) === "") parts.pop();
console.log(parts.slice(-1));
Output
[ 'a', 'b', '' ]
[ '' ]
[ 'b' ]
  • The memory for a large file. A solution that reads all the lines needs memory for the whole file, also when N is small. For a large file, keep only N lines in a queue, as the Python, Go, Rust and C++ solutions do.

Code

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

first_and_last_lines.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

"""Gets the first lines and the last lines of a text file in one pass."""

from collections import deque
from os import PathLike


def first_and_last_lines(path: str | PathLike[str], count: int) -> tuple[list[str], list[str]]:
    """Returns the first count lines and the last count lines of the UTF-8 file at path.

    If the file has fewer than count lines, each list has all the lines. A line
    ends at LF, and the LF is not part of it. A last line with no LF is a line
    too. Raises FileNotFoundError if the file does not exist.
    """
    first: list[str] = []
    # A deque with maxlen=count drops its oldest line when a new line comes, so
    # it holds the last count lines that it has seen.
    last: deque[str] = deque(maxlen=count)
    # With newline="\n", only LF ends a line, and a CR stays in the line.
    with open(path, encoding="utf-8", newline="\n") as f:
        for line in f:
            line = line.removesuffix("\n")
            if len(first) < count:
                first.append(line)
            last.append(line)
    return first, list(last)
test_first_and_last_lines.py 41 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

import pytest

from first_and_last_lines import first_and_last_lines

# name: (the bytes of the file, the count, the first lines, the last lines)
CASES = {
    "two": (b"a\nb\nc\nd\ne\n", 2, ["a", "b"], ["d", "e"]),
    "one": (b"first\nmiddle\nlast\n", 1, ["first"], ["last"]),
    "ten": ("".join(f"{i}\n" for i in range(1, 13)).encode(), 10,
            [str(i) for i in range(1, 11)], [str(i) for i in range(3, 13)]),
    "empty": (b"", 2, [], []),
    "zero": (b"a\nb\n", 0, [], []),
    "short": (b"a\nb\n", 5, ["a", "b"], ["a", "b"]),
    "exact": (b"a\nb\n", 2, ["a", "b"], ["a", "b"]),
    "overlap": (b"a\nb\nc\n", 2, ["a", "b"], ["b", "c"]),
    "one-line": (b"a\n", 1, ["a"], ["a"]),
    "empty-lines": (b"\n\na\n\n", 1, [""], [""]),
    "only-newline": (b"\n", 1, [""], [""]),
    "no-final-newline": (b"a\nb\nc", 1, ["a"], ["c"]),
    "crlf": (b"a\r\nb\r\n", 1, ["a\r"], ["b\r"]),
    "non-ascii": ("caf\u00e9\nna\u00efve\nzo\u00eb\n".encode(), 1, ["caf\u00e9"], ["zo\u00eb"]),
    # 100000 lines with the numbers 0 to 99999.
    "many-lines": ("".join(f"{i}\n" for i in range(100000)).encode(), 3,
                   ["0", "1", "2"], ["99997", "99998", "99999"]),
}


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path, name):
    data, count, first, last = CASES[name]
    path = tmp_path / "input.txt"
    path.write_bytes(data)
    assert first_and_last_lines(path, count) == (first, last)


def test_not_found(tmp_path):
    with pytest.raises(FileNotFoundError):
        first_and_last_lines(tmp_path / "missing.txt", 1)
first_and_last_lines.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

#include "first_and_last_lines.hpp"

#include <deque>
#include <fstream>

std::expected<FirstAndLast, LinesError> first_and_last_lines(const std::filesystem::path& path,
                                                             std::size_t count) {
    // Binary mode keeps each CR. In text mode, some systems change CRLF to LF.
    std::ifstream in(path, std::ios::binary);
    if (!in) {
        return std::unexpected(LinesError::cannot_open);
    }
    std::vector<std::string> first;
    // last holds the last count lines that the loop has seen. When it is full,
    // pop_front removes the oldest line before push_back adds the new one.
    std::deque<std::string> last;
    std::string line;
    // getline removes the LF. At the end of the file, it fails only if it
    // read no characters, so a last line with no LF is a line too.
    while (count > 0 && std::getline(in, line)) {
        if (first.size() < count) {
            first.push_back(line);
        }
        if (last.size() == count) {
            last.pop_front();
        }
        last.push_back(std::move(line));
    }
    if (in.bad()) {
        return std::unexpected(LinesError::read_failed);
    }
    return FirstAndLast{std::move(first), {last.begin(), last.end()}};
}
first_and_last_lines.hpp 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.
// since: C++23 (std::expected)

#pragma once

#include <cstddef>
#include <expected>
#include <filesystem>
#include <string>
#include <utility>
#include <vector>

enum class LinesError { cannot_open, read_failed };

// The first lines and the last lines of a file.
using FirstAndLast = std::pair<std::vector<std::string>, std::vector<std::string>>;

// Returns the first count lines and the last count lines of the file at path.
// If the file has fewer than count lines, each vector has all the lines. A
// line ends at LF, and the LF is not part of it. A last line with no LF is a
// line too.
std::expected<FirstAndLast, LinesError> first_and_last_lines(const std::filesystem::path& path,
                                                             std::size_t count);
test_first_and_last_lines.cpp 86 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

#include <cstdio>
#include <fstream>
#include <string>
#include <vector>

#include "first_and_last_lines.hpp"

namespace {

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

void write(const std::string& data) {
    std::ofstream out(input, std::ios::binary);
    out.write(data.data(), static_cast<std::streamsize>(data.size()));
}

// The numbers from and up to to, but not to.
std::vector<std::string> numbers(int from, int to) {
    std::vector<std::string> v;
    for (int i = from; i < to; i++) {
        v.push_back(std::to_string(i));
    }
    return v;
}

std::string text(const std::vector<std::string>& lines) {
    std::string s;
    for (const auto& l : lines) {
        s += l + "\n";
    }
    return s;
}

struct test_case {
    const char* name;
    std::string data;
    std::size_t count;
    std::vector<std::string> first;
    std::vector<std::string> last;
};

}  // namespace

int main() {
    const std::vector<test_case> cases = {
        {"two", "a\nb\nc\nd\ne\n", 2, {"a", "b"}, {"d", "e"}},
        {"one", "first\nmiddle\nlast\n", 1, {"first"}, {"last"}},
        {"ten", text(numbers(1, 13)), 10, numbers(1, 11), numbers(3, 13)},
        {"empty", "", 2, {}, {}},
        {"zero", "a\nb\n", 0, {}, {}},
        {"short", "a\nb\n", 5, {"a", "b"}, {"a", "b"}},
        {"exact", "a\nb\n", 2, {"a", "b"}, {"a", "b"}},
        {"overlap", "a\nb\nc\n", 2, {"a", "b"}, {"b", "c"}},
        {"one-line", "a\n", 1, {"a"}, {"a"}},
        {"empty-lines", "\n\na\n\n", 1, {""}, {""}},
        {"only-newline", "\n", 1, {""}, {""}},
        {"no-final-newline", "a\nb\nc", 1, {"a"}, {"c"}},
        {"crlf", "a\r\nb\r\n", 1, {"a\r"}, {"b\r"}},
        // U+00E9 is C3 A9, U+00EF is C3 AF, and U+00EB is C3 AB.
        {"non-ascii", "caf\xc3\xa9\nna\xc3\xafve\nzo\xc3\xab\n", 1, {"caf\xc3\xa9"}, {"zo\xc3\xab"}},
        // 100000 lines with the numbers 0 to 99999.
        {"many-lines", text(numbers(0, 100000)), 3, numbers(0, 3), numbers(99997, 100000)},
    };
    int failed = 0;
    for (const auto& c : cases) {
        write(c.data);
        auto got = first_and_last_lines(input, c.count);
        if (!got || got->first != c.first || got->second != c.last) {
            std::fprintf(stderr, "case %s failed\n", c.name);
            failed++;
        }
    }
    auto missing = first_and_last_lines("no/such/dir/missing.txt", 1);
    if (missing || missing.error() != LinesError::cannot_open) {
        std::fprintf(stderr, "case not-found failed\n");
        failed++;
    }
    std::filesystem::remove(input);
    if (failed == 0) {
        std::puts("ok");
    }
    return failed == 0 ? 0 : 1;
}
FirstAndLastLines.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/** Gets the first lines and the last lines of a text file. */
public final class FirstAndLastLines {
  private FirstAndLastLines() {}

  /** The first lines and the last lines of a file. */
  public record Ends(List<String> first, List<String> last) {}

  /**
   * Returns the first count lines and the last count lines of the UTF-8 file at path. If the file
   * has fewer than count lines, each list has all the lines. A line ends at LF, and the LF is not
   * part of it. A last line with no LF is a line too.
   *
   * @throws java.nio.file.NoSuchFileException if the file does not exist
   */
  public static Ends read(Path path, int count) throws IOException {
    byte[] data = Files.readAllBytes(path);
    List<String> lines = new ArrayList<>();
    int start = 0;
    while (start < data.length) {
      int end = start;
      while (end < data.length && data[end] != '\n') {
        end++;
      }
      lines.add(new String(data, start, end - start, StandardCharsets.UTF_8));
      start = end + 1;
    }
    int take = Math.min(count, lines.size());
    // subList gives a view of the list, not a copy. List.copyOf makes a copy,
    // so the result does not keep all the lines of the file in memory.
    return new Ends(
        List.copyOf(lines.subList(0, take)),
        List.copyOf(lines.subList(lines.size() - take, lines.size())));
  }
}
FirstAndLastLinesTest.java 69 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

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

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
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 FirstAndLastLinesTest {
  @TempDir Path dir;

  // The numbers from and up to to, but not to.
  private static List<String> numbers(int from, int to) {
    return IntStream.range(from, to).mapToObj(Integer::toString).toList();
  }

  private static String text(List<String> lines) {
    return lines.stream().map(l -> l + "\n").collect(Collectors.joining());
  }

  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("two", "a\nb\nc\nd\ne\n", 2, List.of("a", "b"), List.of("d", "e")),
        Arguments.of("one", "first\nmiddle\nlast\n", 1, List.of("first"), List.of("last")),
        Arguments.of("ten", text(numbers(1, 13)), 10, numbers(1, 11), numbers(3, 13)),
        Arguments.of("empty", "", 2, List.of(), List.of()),
        Arguments.of("zero", "a\nb\n", 0, List.of(), List.of()),
        Arguments.of("short", "a\nb\n", 5, List.of("a", "b"), List.of("a", "b")),
        Arguments.of("exact", "a\nb\n", 2, List.of("a", "b"), List.of("a", "b")),
        Arguments.of("overlap", "a\nb\nc\n", 2, List.of("a", "b"), List.of("b", "c")),
        Arguments.of("one-line", "a\n", 1, List.of("a"), List.of("a")),
        Arguments.of("empty-lines", "\n\na\n\n", 1, List.of(""), List.of("")),
        Arguments.of("only-newline", "\n", 1, List.of(""), List.of("")),
        Arguments.of("no-final-newline", "a\nb\nc", 1, List.of("a"), List.of("c")),
        Arguments.of("crlf", "a\r\nb\r\n", 1, List.of("a\r"), List.of("b\r")),
        Arguments.of(
            "non-ascii", "caf\u00e9\nna\u00efve\nzo\u00eb\n", 1, List.of("caf\u00e9"), List.of("zo\u00eb")),
        // 100000 lines with the numbers 0 to 99999.
        Arguments.of("many-lines", text(numbers(0, 100000)), 3, numbers(0, 3), numbers(99997, 100000)));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void read(String name, String text, int count, List<String> first, List<String> last)
      throws IOException {
    Path path = dir.resolve("input.txt");
    Files.writeString(path, text, StandardCharsets.UTF_8);
    assertEquals(new FirstAndLastLines.Ends(first, last), FirstAndLastLines.read(path, count), name);
  }

  @Test
  void notFound() {
    assertThrows(
        NoSuchFileException.class, () -> FirstAndLastLines.read(dir.resolve("missing.txt"), 1));
  }
}
first_and_last_lines.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

#include "first_and_last_lines.h"

#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

// read_all reads the whole stream into a new buffer. The buffer has at least
// one free byte after the data, for a NUL.
static char *read_all(FILE *f, size_t *size) {
    size_t cap = 4096;
    size_t used = 0;
    char *data = malloc(cap);
    if (data == NULL) {
        errno = ENOMEM;
        return NULL;
    }
    for (;;) {
        if (cap - used < 2) {
            char *bigger = cap <= SIZE_MAX / 2 ? realloc(data, cap * 2) : NULL;
            if (bigger == NULL) {
                free(data);
                errno = ENOMEM;
                return NULL;
            }
            data = bigger;
            cap *= 2;
        }
        size_t n = fread(data + used, 1, cap - used - 1, f);
        used += n;
        if (n == 0) {
            break;
        }
    }
    if (ferror(f)) {
        free(data);
        errno = EIO;
        return NULL;
    }
    *size = used;
    return data;
}

int first_and_last_lines(const char *path, size_t count, struct first_and_last *out) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        return -1;
    }
    size_t size;
    char *data = read_all(f, &size);
    int e = errno;
    fclose(f);
    if (data == NULL) {
        errno = e;
        return -1;
    }
    // Each LF ends a line. A last line with no LF is one more line.
    size_t n = 0;
    for (size_t i = 0; i < size; i++) {
        n += data[i] == '\n';
    }
    if (size > 0 && data[size - 1] != '\n') {
        n++;
    }
    struct line *lines = n > 0 ? malloc(n * sizeof *lines) : NULL;
    if (n > 0 && lines == NULL) {
        free(data);
        errno = ENOMEM;
        return -1;
    }
    // Change each LF to a NUL, so that each line is a C string. The end of the
    // file ends a last line with no LF.
    size_t k = 0;
    size_t start = 0;
    for (size_t i = 0; i <= size; i++) {
        if (i < size ? data[i] != '\n' : start == size) {
            continue;
        }
        data[i] = '\0';
        lines[k++] = (struct line){data + start, i - start};
        start = i + 1;
    }
    // The first part starts at line 0, and the last part ends at line n - 1. An
    // empty file has no array of lines, and lines is NULL.
    size_t take = count < n ? count : n;
    const struct line *last = lines == NULL ? NULL : lines + (n - take);
    *out = (struct first_and_last){lines, take, last, take, lines, data};
    return 0;
}

void first_and_last_free(struct first_and_last *r) {
    free(r->lines);
    free(r->data);
    *r = (struct first_and_last){NULL, 0, NULL, 0, NULL, NULL};
}
first_and_last_lines.h 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

#ifndef FIRST_AND_LAST_LINES_H
#define FIRST_AND_LAST_LINES_H

#include <stddef.h>

// A line of the file: text is a C string with no LF, and len is its length.
struct line {
    const char *text;
    size_t len;
};

// The first lines and the last lines of a file. first and last point into
// lines, which holds all the lines of the file, and each line points into
// data, which holds all the bytes of the file. The two parts can overlap.
struct first_and_last {
    const struct line *first;
    size_t first_len;
    const struct line *last;
    size_t last_len;
    struct line *lines;
    char *data;
};

// first_and_last_lines reads the file at path and puts its first count lines
// and its last count lines into out. If the file has fewer than count lines,
// each part has all the lines. A line ends at LF, and the LF is not part of
// it. A last line with no LF is a line too. It returns 0, or -1 and sets
// errno: ENOENT if the file does not exist.
int first_and_last_lines(const char *path, size_t count, struct first_and_last *out);

// first_and_last_free frees the memory of the result.
void first_and_last_free(struct first_and_last *r);

#endif
test_first_and_last_lines.c 97 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

#include "first_and_last_lines.h"

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

static const char *path = "first_and_last_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);
}

static void check_part(const char *name, const char *part, const struct line *got, size_t got_len,
                       const char *const *want, size_t n) {
    if (got_len != n) {
        fprintf(stderr, "case %s: the %s part has %zu lines, want %zu\n", name, part, got_len, n);
        exit(1);
    }
    for (size_t i = 0; i < n; i++) {
        if (got[i].len != strlen(want[i]) || strcmp(got[i].text, want[i]) != 0) {
            fprintf(stderr, "case %s: line %zu of the %s part is \"%s\", want \"%s\"\n", name, i, part, got[i].text,
                    want[i]);
            exit(1);
        }
    }
}

// The lines of the result, first and last, in one array: n first lines, then
// n last lines. Each case has the same number of lines in the two parts.
static void check(const char *name, const char *data, size_t size, size_t count, const char *const *want,
                  size_t n) {
    write_file(data, size);
    struct first_and_last got;
    if (first_and_last_lines(path, count, &got) != 0) {
        fprintf(stderr, "case %s: error %d\n", name, errno);
        exit(1);
    }
    check_part(name, "first", got.first, got.first_len, want, n);
    check_part(name, "last", got.last, got.last_len, n > 0 ? want + n : NULL, n);
    first_and_last_free(&got);
}

// sizeof counts the bytes of the literal, but not the final NUL. The first
// lines and then the last lines that the case wants come after the count.
#define CASE(name, data, count, ...)                                                          \
    do {                                                                                      \
        static const char *const want[] = {__VA_ARGS__};                                      \
        check(name, data, sizeof(data) - 1, count, want, sizeof want / sizeof want[0] / 2); \
    } while (0)

int main(void) {
    CASE("two", "a\nb\nc\nd\ne\n", 2, "a", "b", "d", "e");
    CASE("one", "first\nmiddle\nlast\n", 1, "first", "last");
    CASE("ten", "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n", 10, "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
         "3", "4", "5", "6", "7", "8", "9", "10", "11", "12");
    check("empty", "", 0, 2, NULL, 0);
    check("zero", "a\nb\n", 4, 0, NULL, 0);
    CASE("short", "a\nb\n", 5, "a", "b", "a", "b");
    CASE("exact", "a\nb\n", 2, "a", "b", "a", "b");
    CASE("overlap", "a\nb\nc\n", 2, "a", "b", "b", "c");
    CASE("one-line", "a\n", 1, "a", "a");
    CASE("empty-lines", "\n\na\n\n", 1, "", "");
    CASE("only-newline", "\n", 1, "", "");
    CASE("no-final-newline", "a\nb\nc", 1, "a", "c");
    CASE("crlf", "a\r\nb\r\n", 1, "a\r", "b\r");
    // U+00E9 is C3 A9, and U+00EB is C3 AB.
    CASE("non-ascii", "caf\xc3\xa9\nna\xc3\xafve\nzo\xc3\xab\n", 1, "caf\xc3\xa9", "zo\xc3\xab");

    // 100000 lines with the numbers 0 to 99999.
    size_t cap = 100000 * 6;
    char *data = malloc(cap);
    assert(data != NULL);
    size_t size = 0;
    for (int i = 0; i < 100000; i++) {
        size += (size_t)snprintf(data + size, cap - size, "%d\n", i);
    }
    check("many-lines", data, size, 3, (const char *const[]){"0", "1", "2", "99997", "99998", "99999"}, 3);
    free(data);

    struct first_and_last got;
    errno = 0;
    if (first_and_last_lines("no/such/dir/missing.txt", 1, &got) != -1 || errno != ENOENT) {
        fprintf(stderr, "case not-found: want -1 and ENOENT\n");
        return 1;
    }
    remove(path);
    puts("ok");
    return 0;
}
FirstAndLastLines.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

using System.Text;

/// <summary>Gets the first lines and the last lines of a text file.</summary>
public static class FirstAndLastLines
{
    /// <summary>
    /// Returns the first count lines and the last count lines of the UTF-8 file at path. If the
    /// file has fewer than count lines, each list has all the lines. A line ends at LF, and the
    /// LF is not part of it. A last line with no LF is a line too.
    /// </summary>
    /// <exception cref="FileNotFoundException">The file does not exist.</exception>
    public static (List<string> First, List<string> Last) Read(string path, int count)
    {
        byte[] data = File.ReadAllBytes(path);
        var lines = new List<string>();
        int start = 0;
        while (start < data.Length)
        {
            int end = Array.IndexOf(data, (byte)'\n', start);
            if (end < 0)
            {
                end = data.Length;
            }
            lines.Add(Encoding.UTF8.GetString(data, start, end - start));
            start = end + 1;
        }
        int take = Math.Min(count, lines.Count);
        // GetRange takes a start index and a number of items, not an end index.
        return (lines.GetRange(0, take), lines.GetRange(lines.Count - take, take));
    }
}
FirstAndLastLinesTests.cs 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

using System.Text;
using Xunit;

public sealed class FirstAndLastLinesTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("first-and-last-").FullName;

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

    // The numbers from and up to to, but not to.
    private static string[] Numbers(int from, int to) =>
        Enumerable.Range(from, to - from).Select(i => $"{i}").ToArray();

    private static string Text(string[] lines) => string.Concat(lines.Select(l => l + "\n"));

    public static TheoryData<string, string, int, string[], string[]> Cases => new()
    {
        { "two", "a\nb\nc\nd\ne\n", 2, ["a", "b"], ["d", "e"] },
        { "one", "first\nmiddle\nlast\n", 1, ["first"], ["last"] },
        { "ten", Text(Numbers(1, 13)), 10, Numbers(1, 11), Numbers(3, 13) },
        { "empty", "", 2, [], [] },
        { "zero", "a\nb\n", 0, [], [] },
        { "short", "a\nb\n", 5, ["a", "b"], ["a", "b"] },
        { "exact", "a\nb\n", 2, ["a", "b"], ["a", "b"] },
        { "overlap", "a\nb\nc\n", 2, ["a", "b"], ["b", "c"] },
        { "one-line", "a\n", 1, ["a"], ["a"] },
        { "empty-lines", "\n\na\n\n", 1, [""], [""] },
        { "only-newline", "\n", 1, [""], [""] },
        { "no-final-newline", "a\nb\nc", 1, ["a"], ["c"] },
        { "crlf", "a\r\nb\r\n", 1, ["a\r"], ["b\r"] },
        { "non-ascii", "caf\u00e9\nna\u00efve\nzo\u00eb\n", 1, ["caf\u00e9"], ["zo\u00eb"] },
        // 100000 lines with the numbers 0 to 99999.
        { "many-lines", Text(Numbers(0, 100000)), 3, Numbers(0, 3), Numbers(99997, 100000) },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Read(string name, string text, int count, string[] first, string[] last)
    {
        string path = Path.Combine(dir, "input.txt");
        // UTF8Encoding(false) writes no byte order mark.
        File.WriteAllText(path, text, new UTF8Encoding(false));
        var got = FirstAndLastLines.Read(path, count);
        Assert.Equal(first, got.First);
        Assert.Equal(last, got.Last);
        _ = name;
    }

    [Fact]
    public void NotFound()
    {
        Assert.Throws<FileNotFoundException>(() => FirstAndLastLines.Read(Path.Combine(dir, "missing.txt"), 1));
    }
}
firstAndLastLines.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

import { readFileSync } from "node:fs";

// Returns [first, last]: the first count lines and the last count lines of the
// UTF-8 file at path. If the file has fewer than count lines, each array has
// all the lines. A line ends at LF, and the LF is not part of it. A last line
// with no LF is a line too. A missing file throws an error whose code is
// "ENOENT".
export function firstAndLastLines(path, count) {
  const lines = readFileSync(path, "utf8").split("\n");
  // The part after the last LF is empty, or it is a last line with no LF.
  if (lines.at(-1) === "") lines.pop();
  // slice(-count) is not correct: slice(-0) is slice(0), which is all the lines.
  const start = Math.max(lines.length - count, 0);
  return [lines.slice(0, count), lines.slice(start)];
}
firstAndLastLines.test.js 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

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

const dir = mkdtempSync(join(tmpdir(), "first-and-last-"));
after(() => rmSync(dir, { recursive: true }));

const lines = (from, to) => Array.from({ length: to - from }, (_, i) => `${from + i}`);
const numbers = lines(0, 100000).map((s) => `${s}\n`).join("");

// [name, the text of the file, the count, the first lines, the last lines]
const cases = [
  ["two", "a\nb\nc\nd\ne\n", 2, ["a", "b"], ["d", "e"]],
  ["one", "first\nmiddle\nlast\n", 1, ["first"], ["last"]],
  ["ten", lines(1, 13).map((s) => `${s}\n`).join(""), 10, lines(1, 11), lines(3, 13)],
  ["empty", "", 2, [], []],
  ["zero", "a\nb\n", 0, [], []],
  ["short", "a\nb\n", 5, ["a", "b"], ["a", "b"]],
  ["exact", "a\nb\n", 2, ["a", "b"], ["a", "b"]],
  ["overlap", "a\nb\nc\n", 2, ["a", "b"], ["b", "c"]],
  ["one-line", "a\n", 1, ["a"], ["a"]],
  ["empty-lines", "\n\na\n\n", 1, [""], [""]],
  ["only-newline", "\n", 1, [""], [""]],
  ["no-final-newline", "a\nb\nc", 1, ["a"], ["c"]],
  ["crlf", "a\r\nb\r\n", 1, ["a\r"], ["b\r"]],
  ["non-ascii", "caf\u00e9\nna\u00efve\nzo\u00eb\n", 1, ["caf\u00e9"], ["zo\u00eb"]],
  // 100000 lines with the numbers 0 to 99999.
  ["many-lines", numbers, 3, ["0", "1", "2"], ["99997", "99998", "99999"]],
];

for (const [name, text, count, first, last] of cases) {
  test(name, () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, text, "utf8");
    assert.deepEqual(firstAndLastLines(path, count), [first, last]);
  });
}

test("not-found", () => {
  assert.throws(() => firstAndLastLines(join(dir, "missing.txt"), 1), { code: "ENOENT" });
});
firstAndLastLines.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

import { readFileSync } from "node:fs";

// Returns [first, last]: the first count lines and the last count lines of the
// UTF-8 file at path. If the file has fewer than count lines, each array has
// all the lines. A line ends at LF, and the LF is not part of it. A last line
// with no LF is a line too. A missing file throws an error whose code is
// "ENOENT".
export function firstAndLastLines(path: string, count: number): [string[], string[]] {
  const lines = readFileSync(path, "utf8").split("\n");
  // The part after the last LF is empty, or it is a last line with no LF.
  if (lines.at(-1) === "") lines.pop();
  // slice(-count) is not correct: slice(-0) is slice(0), which is all the lines.
  const start = Math.max(lines.length - count, 0);
  return [lines.slice(0, count), lines.slice(start)];
}
firstAndLastLines.test.ts 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

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

const dir = mkdtempSync(join(tmpdir(), "first-and-last-"));
after(() => rmSync(dir, { recursive: true }));

const lines = (from: number, to: number): string[] => Array.from({ length: to - from }, (_, i) => `${from + i}`);
const numbers = lines(0, 100000).map((s) => `${s}\n`).join("");

// [name, the text of the file, the count, the first lines, the last lines]
const cases: [string, string, number, string[], string[]][] = [
  ["two", "a\nb\nc\nd\ne\n", 2, ["a", "b"], ["d", "e"]],
  ["one", "first\nmiddle\nlast\n", 1, ["first"], ["last"]],
  ["ten", lines(1, 13).map((s) => `${s}\n`).join(""), 10, lines(1, 11), lines(3, 13)],
  ["empty", "", 2, [], []],
  ["zero", "a\nb\n", 0, [], []],
  ["short", "a\nb\n", 5, ["a", "b"], ["a", "b"]],
  ["exact", "a\nb\n", 2, ["a", "b"], ["a", "b"]],
  ["overlap", "a\nb\nc\n", 2, ["a", "b"], ["b", "c"]],
  ["one-line", "a\n", 1, ["a"], ["a"]],
  ["empty-lines", "\n\na\n\n", 1, [""], [""]],
  ["only-newline", "\n", 1, [""], [""]],
  ["no-final-newline", "a\nb\nc", 1, ["a"], ["c"]],
  ["crlf", "a\r\nb\r\n", 1, ["a\r"], ["b\r"]],
  ["non-ascii", "caf\u00e9\nna\u00efve\nzo\u00eb\n", 1, ["caf\u00e9"], ["zo\u00eb"]],
  // 100000 lines with the numbers 0 to 99999.
  ["many-lines", numbers, 3, ["0", "1", "2"], ["99997", "99998", "99999"]],
];

for (const [name, text, count, first, last] of cases) {
  test(name, () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, text, "utf8");
    assert.deepEqual(firstAndLastLines(path, count), [first, last]);
  });
}

test("not-found", () => {
  assert.throws(() => firstAndLastLines(join(dir, "missing.txt"), 1), { code: "ENOENT" });
});
first_and_last_lines.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

// Package firstandlast gets the first lines and the last lines of a text file
// in one pass.
package firstandlast

import (
	"bufio"
	"errors"
	"io"
	"os"
	"strings"
)

// FirstAndLastLines returns the first count lines and the last count lines of
// the UTF-8 file at path. If the file has fewer than count lines, each slice
// has all the lines. A line ends at LF, and the LF is not part of it. A last
// line with no LF is a line too. A missing file gives an error that matches
// fs.ErrNotExist.
func FirstAndLastLines(path string, count int) (first, last []string, err error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, nil, err
	}
	defer f.Close()
	r := bufio.NewReader(f)
	first = []string{}
	// ring holds the last count lines. The line number n goes to ring[n%count],
	// over the line that came count lines before it.
	ring := make([]string, count)
	n := 0
	for {
		// ReadString returns the line with its LF, or the last line with no
		// LF together with io.EOF.
		line, err := r.ReadString('\n')
		if err != nil && !errors.Is(err, io.EOF) {
			return nil, nil, err
		}
		if line != "" && count > 0 {
			line = strings.TrimSuffix(line, "\n")
			if n < count {
				first = append(first, line)
			}
			ring[n%count] = line
			n++
		}
		if err != nil {
			break
		}
	}
	// The oldest line in the ring is at n%count, if the ring is full.
	last = make([]string, 0, min(n, count))
	for i := max(n-count, 0); i < n; i++ {
		last = append(last, ring[i%count])
	}
	return first, last, nil
}
first_and_last_lines_test.go 79 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

package firstandlast

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

// numbers returns the numbers from and up to to, but not to, one on each line.
func numbers(from, to int) []string {
	s := []string{}
	for i := from; i < to; i++ {
		s = append(s, strconv.Itoa(i))
	}
	return s
}

func text(lines []string) string {
	var b strings.Builder
	for _, l := range lines {
		b.WriteString(l + "\n")
	}
	return b.String()
}

func TestFirstAndLastLines(t *testing.T) {
	cases := []struct {
		name, text  string
		count       int
		first, last []string
	}{
		{"two", "a\nb\nc\nd\ne\n", 2, []string{"a", "b"}, []string{"d", "e"}},
		{"one", "first\nmiddle\nlast\n", 1, []string{"first"}, []string{"last"}},
		{"ten", text(numbers(1, 13)), 10, numbers(1, 11), numbers(3, 13)},
		{"empty", "", 2, []string{}, []string{}},
		{"zero", "a\nb\n", 0, []string{}, []string{}},
		{"short", "a\nb\n", 5, []string{"a", "b"}, []string{"a", "b"}},
		{"exact", "a\nb\n", 2, []string{"a", "b"}, []string{"a", "b"}},
		{"overlap", "a\nb\nc\n", 2, []string{"a", "b"}, []string{"b", "c"}},
		{"one-line", "a\n", 1, []string{"a"}, []string{"a"}},
		{"empty-lines", "\n\na\n\n", 1, []string{""}, []string{""}},
		{"only-newline", "\n", 1, []string{""}, []string{""}},
		{"no-final-newline", "a\nb\nc", 1, []string{"a"}, []string{"c"}},
		{"crlf", "a\r\nb\r\n", 1, []string{"a\r"}, []string{"b\r"}},
		{"non-ascii", "caf\u00e9\nna\u00efve\nzo\u00eb\n", 1, []string{"caf\u00e9"}, []string{"zo\u00eb"}},
		// 100000 lines with the numbers 0 to 99999.
		{"many-lines", text(numbers(0, 100000)), 3, []string{"0", "1", "2"}, []string{"99997", "99998", "99999"}},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			path := filepath.Join(t.TempDir(), "input.txt")
			if err := os.WriteFile(path, []byte(c.text), 0o644); err != nil {
				t.Fatal(err)
			}
			first, last, err := FirstAndLastLines(path, c.count)
			if err != nil {
				t.Fatal(err)
			}
			if !reflect.DeepEqual(first, c.first) || !reflect.DeepEqual(last, c.last) {
				t.Errorf("got %q and %q, want %q and %q", first, last, c.first, c.last)
			}
		})
	}
}

func TestNotFound(t *testing.T) {
	_, _, err := FirstAndLastLines(filepath.Join(t.TempDir(), "missing.txt"), 1)
	if !errors.Is(err, fs.ErrNotExist) {
		t.Errorf("got %v, want fs.ErrNotExist", err)
	}
}
first_and_last_lines.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

//! Gets the first lines and the last lines of a text file in one pass.

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

/// Returns the first `count` lines and the last `count` lines of the UTF-8
/// file at `path`.
///
/// If the file has fewer than `count` lines, each vector has all the lines. A
/// line ends at LF, and the LF is not part of it. A last line with no LF is a
/// line too. A missing file gives an error of kind `NotFound`.
pub fn first_and_last_lines(
    path: impl AsRef<Path>,
    count: usize,
) -> io::Result<(Vec<String>, Vec<String>)> {
    let mut reader = BufReader::new(File::open(path)?);
    let mut first = Vec::new();
    // last holds the last `count` lines that the loop has seen. When it is
    // full, pop_front removes the oldest line before push_back adds the new one.
    let mut last = VecDeque::with_capacity(count);
    let mut line = String::new();
    // read_line reads up to and with the next LF, so a CR stays in the line.
    // It returns 0 at the end of the file.
    while count > 0 && reader.read_line(&mut line)? > 0 {
        if line.ends_with('\n') {
            line.pop();
        }
        if first.len() < count {
            first.push(line.clone());
        }
        if last.len() == count {
            last.pop_front();
        }
        last.push_back(std::mem::take(&mut line));
    }
    Ok((first, last.into()))
}
tests/first_and_last_lines_test.rs 59 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

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

use algo_first_and_last_lines::first_and_last_lines;

fn temp_file(name: &str, text: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("first-and-last-{}", std::process::id()));
    fs::create_dir_all(&dir).unwrap();
    let path = dir.join(format!("{name}.txt"));
    fs::write(&path, text).unwrap();
    path
}

fn numbers(from: u32, to: u32) -> Vec<String> {
    (from..to).map(|i| i.to_string()).collect()
}

fn text(lines: &[String]) -> String {
    lines.iter().map(|l| format!("{l}\n")).collect()
}

#[test]
fn cases() {
    let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
    let cases: Vec<(&str, String, usize, Vec<String>, Vec<String>)> = vec![
        ("two", "a\nb\nc\nd\ne\n".into(), 2, s(&["a", "b"]), s(&["d", "e"])),
        ("one", "first\nmiddle\nlast\n".into(), 1, s(&["first"]), s(&["last"])),
        ("ten", text(&numbers(1, 13)), 10, numbers(1, 11), numbers(3, 13)),
        ("empty", "".into(), 2, s(&[]), s(&[])),
        ("zero", "a\nb\n".into(), 0, s(&[]), s(&[])),
        ("short", "a\nb\n".into(), 5, s(&["a", "b"]), s(&["a", "b"])),
        ("exact", "a\nb\n".into(), 2, s(&["a", "b"]), s(&["a", "b"])),
        ("overlap", "a\nb\nc\n".into(), 2, s(&["a", "b"]), s(&["b", "c"])),
        ("one-line", "a\n".into(), 1, s(&["a"]), s(&["a"])),
        ("empty-lines", "\n\na\n\n".into(), 1, s(&[""]), s(&[""])),
        ("only-newline", "\n".into(), 1, s(&[""]), s(&[""])),
        ("no-final-newline", "a\nb\nc".into(), 1, s(&["a"]), s(&["c"])),
        ("crlf", "a\r\nb\r\n".into(), 1, s(&["a\r"]), s(&["b\r"])),
        ("non-ascii", "caf\u{e9}\nna\u{ef}ve\nzo\u{eb}\n".into(), 1, s(&["caf\u{e9}"]), s(&["zo\u{eb}"])),
        // 100000 lines with the numbers 0 to 99999.
        ("many-lines", text(&numbers(0, 100000)), 3, numbers(0, 3), numbers(99997, 100000)),
    ];
    for (name, text, count, first, last) in cases {
        let path = temp_file(name, &text);
        let got = first_and_last_lines(&path, count).unwrap();
        assert_eq!(got, (first, last), "case {name}");
        fs::remove_file(path).unwrap();
    }
}

#[test]
fn not_found() {
    let err = first_and_last_lines("no/such/dir/missing.txt", 1).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
}
first_and_last_lines.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

# first_and_last_lines PATH COUNT FIRST LAST
# Puts the first COUNT lines of the file at PATH into the array named FIRST,
# and the last COUNT lines into the array named LAST, with no LF at the end of
# each line. Returns a nonzero status if the file cannot be read. Needs bash
# 4.3 or later, for local -n.
first_and_last_lines() {
  [[ -r $1 && ! -d $1 ]] || { printf 'first_and_last_lines: cannot read %s\n' "$1" >&2; return 1; }
  local -n first_and_last_lines_first=$3 first_and_last_lines_last=$4
  first_and_last_lines_first=()
  first_and_last_lines_last=()
  # POSIX lets head refuse -n 0, and some versions do. So a count of 0 does
  # not run head or tail.
  (($2 > 0)) || return 0
  # mapfile -t removes the LF at the end of each line, but keeps a CR.
  mapfile -t first_and_last_lines_first < <(head -n "$2" -- "$1")
  mapfile -t first_and_last_lines_last < <(tail -n "$2" -- "$1")
}
test_first_and_last_lines.bats 57 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/print-the-first-and-last-lines-of-a-file/.

bats_require_minimum_version 1.5.0

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

# joined ARRAY prints each item of the array named ARRAY with an LF after it,
# and then an x, which keeps the final LFs that $(...) removes.
joined() {
  local -n joined_items=$1
  local item
  for item in "${joined_items[@]}"; do printf '%s\n' "$item"; done
  printf x
}

check() { # check BYTES COUNT FIRST LAST
  printf '%b' "$1" >"$file"
  local -a first last
  first_and_last_lines "$file" "$2" first last
  [ "$(joined first)" = "$(printf '%bx' "$3")" ] || return 1
  [ "$(joined last)" = "$(printf '%bx' "$4")" ]
}

@test "two" { check 'a\nb\nc\nd\ne\n' 2 'a\nb\n' 'd\ne\n'; }
@test "one" { check 'first\nmiddle\nlast\n' 1 'first\n' 'last\n'; }
@test "ten" { check "$(seq 1 12)\n" 10 "$(seq 1 10)\n" "$(seq 3 12)\n"; }
@test "empty" { check '' 2 '' ''; }
@test "zero" { check 'a\nb\n' 0 '' ''; }
@test "short" { check 'a\nb\n' 5 'a\nb\n' 'a\nb\n'; }
@test "exact" { check 'a\nb\n' 2 'a\nb\n' 'a\nb\n'; }
@test "overlap" { check 'a\nb\nc\n' 2 'a\nb\n' 'b\nc\n'; }
@test "one-line" { check 'a\n' 1 'a\n' 'a\n'; }
@test "empty-lines" { check '\n\na\n\n' 1 '\n' '\n'; }
@test "only-newline" { check '\n' 1 '\n' '\n'; }
@test "no-final-newline" { check 'a\nb\nc' 1 'a\n' 'c\n'; }
@test "crlf" { check 'a\r\nb\r\n' 1 'a\r\n' 'b\r\n'; }
@test "non-ascii" { check 'caf\xc3\xa9\nna\xc3\xafve\nzo\xc3\xab\n' 1 'caf\xc3\xa9\n' 'zo\xc3\xab\n'; }

@test "many-lines" {
  seq 0 99999 >"$file"
  local -a first last
  first_and_last_lines "$file" 3 first last
  [ "${first[*]}" = "0 1 2" ]
  [ "${last[*]}" = "99997 99998 99999" ]
}

@test "not-found" {
  local -a first last
  run first_and_last_lines "$BATS_TEST_TMPDIR/missing.txt" 1 first last
  [ "$status" -ne 0 ]
  [ "$output" = "first_and_last_lines: cannot read $BATS_TEST_TMPDIR/missing.txt" ]
}

References

  1. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), head, DESCRIPTION; OPTIONS
  2. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), tail, DESCRIPTION; OPTIONS (-n)
  3. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), Base Definitions, Chapter 3, Definitions, 3.172 Incomplete Line; 3.185 Line
  4. The Python Standard Library, Built-in Functions, open (newline)
  5. The Python Standard Library, collections, deque
  6. MDN Web Docs, Array.prototype.slice(), Parameters
  7. Java SE 25 API, java.util.List, subList
  8. .NET API reference, List<T>.GetRange
  9. Go standard library, package bufio, Reader.ReadString
  10. The Rust Standard Library, std::collections::VecDeque
  11. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), fread, DESCRIPTION
  12. cppreference.com, std::deque
  13. The Python Standard Library, Built-in Types, Common Sequence Operations, note 3
  14. MDN Web Docs, String.prototype.split(), Description

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
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source