Programming Search⌘K

Taskintro

Read a specific line from a file

Also called read line N of a file, get the nth line of a file, sed -n Np, print one line of a file.

Read a UTF-8 file up to line N and return that line, or no line if the file has fewer lines, with line numbers that start at 1 and with only LF as the end of a line.

Task

Read a text file and a line number N, and return line N of the file. Line 1 is the first line. If the file has fewer than N lines, or if N is less than 1, return no line. sed -n 'Np' and awk 'NR == N' do this job in a shell. In awk, NR is "The ordinal number of the current record from the start of input."1

The task needs rules for what a line is. 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."2 The LF is not part of the line in the result. A CR before the LF stays in the line, and a CR that is not before an LF does not end a 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."2
  • An empty line is a line. It is different from no line. The result type tells the two apart: an empty string is an empty line, and null (or None, or an empty Optional) is no line.
  • The code stops at the line. It does not read the rest of the file.

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

Solutions

The method is the same in each language. Read the file one line at a time and count the lines. When the count is N, return the line and stop. If the file ends first, return no line. A file has no index of its lines, so the code must read all the lines before line N to find where line N starts.

  • 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",3 so a CR stays in the line. enumerate(f, start=1) gives each line with its number, and removesuffix('\n') removes the LF. The function returns None if there is no line.
  • 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: MDN says that if the separator is at the end of the string, there is "an empty (i.e., zero length) string appearing at the first (or last) position of the returned array."4 The function returns lines[number - 1], or null if number is not an integer from 1 to the number of lines. This solution reads the whole file, because the code is short. The TypeScript file adds types only.
  • Java. A BufferedInputStream gives the bytes one at a time. The code counts the LF bytes, keeps the bytes of line N in a ByteArrayOutputStream, and decodes them as UTF-8 at the LF. The result is an Optional<String>. The code does not use BufferedReader.readLine, because it also ends a line at a CR (see Pitfalls).
  • C#. A BufferedStream gives the bytes. ReadByte "Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream."5 The code keeps the bytes of line N in a MemoryStream and decodes them with Encoding.UTF8.GetString. The result is a string?. The code does not use StreamReader.ReadLine, for the same reason as in Java.
  • 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."6 strings.TrimSuffix removes the LF. ReadLine returns the line, a bool that is false if there is no line, and an error. The code does not use bufio.Scanner, because its ScanLines removes a CR before the LF: "The end-of-line marker is one optional carriage return followed by one mandatory newline."6 A Scanner also has a maximum line length.
  • Rust. BufRead::read_line "Reads all bytes until a newline (the 0xA byte) is reached, and append them to the provided String buffer."7 It returns 0 at the end of the file. The code calls it N times, and then pop removes the LF. The result is an io::Result<Option<String>>. The code does not use lines, because "Each string returned will not have a newline byte (the 0xA byte) or CRLF",7 so a CR before the LF goes away.
  • C. getline reads each line into a buffer that it grows as necessary. POSIX says that getdelim "shall read from stream until it encounters a character matching the delimiter character",8 and that getline is getdelim with an LF as the delimiter. The return value is "the number of bytes written into the buffer, including the delimiter character if one was encountered before EOF",8 so the code knows the length of the line and can remove the LF. read_line returns 1 and gives the line and its length, which the caller frees. It returns 0 if there is no line, or -1 with errno set on an error.
  • C++. std::getline reads a binary std::ifstream one line at a time and removes the LF. At the end of the file, it fails only "If no characters were extracted for whatever reason (not even the discarded delimiter)",9 so a last line with no LF is a line too. The result is a std::expected (C++23) that holds a std::optional<std::string>, and the errors are cannot_open and read_failed.
  • Bash. The awk program NR == n { print; found = 1; exit } END { exit !found } prints line N, and -v sets the awk variable n to N. "The exit statement shall invoke all END actions in the order in which they occur in the program source and then terminate the program without reading further input."1 So awk stops at the line, and the END action gives the status: 0 if it found the line, 1 if not. The file comes on the standard input, not as an operand. For awk, an operand that starts with a letter or an underscore, followed by letters, digits or underscores and then =, is an assignment, not a file.1 So a file with the name x=1 would not be read. The function returns 2 if the file cannot be read.

Edge cases

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

  • first, middle and last: lines 1, 2 and 3 of a, b, c are a, b and c.
  • past-the-end: line 3 of a file with two lines is no line.
  • zero and negative: line 0 and line -1 are no line. Line numbers start at 1.
  • empty: line 1 of an empty file is no line.
  • empty-line and only-newline: line 2 of a, empty, b is an empty line, and line 1 of a file with one LF is an empty line.
  • no-final-newline: line 2 of a, b with no LF at the end is b.
  • crlf: line 1 of a CRLF, b CRLF is a CR.
  • lone-cr: line 2 of a CR b LF c LF is c, because the CR does not end a line.
  • non-ascii: line 2 of café, zoë is zoë.

The tests also write a file of 100000 lines with the numbers 0 to 99999. Line 100000 must be 99999, and line 100001 must be no line. 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

  • Line numbers start at 1, and indexes start at 0. Line N is at index N - 1 in a list of lines. If the code does not subtract 1, it returns the next line, and for the last line it reads past the end of the list.
  • head | tail gives the last line of a short file. head -n N FILE | tail -n 1 is a common way to get line N. But for head, "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."10 So if the file has fewer than N lines, tail -n 1 gives the last line of the file, not no line. sed -n 'Np' and awk 'NR == N' give no output:
f=$(mktemp)
printf 'a\nb\nc\n' >"$f"
echo "head -n 5 | tail -n 1:"
head -n 5 "$f" | tail -n 1
echo "sed -n 5p:"
sed -n 5p "$f"
echo "awk 'NR == 5':"
awk 'NR == 5' "$f"
rm "$f"
Output
head -n 5 | tail -n 1:
c
sed -n 5p:
awk 'NR == 5':
  • linecache.getline hides the difference between an empty line and no line. The function "will return '' on errors (the terminating newline character will be included for lines that are found)."11 So an empty line is '\n' and no line is ''. If the code removes the LF first, the two values are the same:
import linecache, os, tempfile

fd, path = tempfile.mkstemp()
with os.fdopen(fd, "w") as f:
    f.write("a\n\nb\n")
for number in [2, 9]:
    line = linecache.getline(path, number)
    print(number, repr(line), repr(line.rstrip("\n")))
os.remove(path)
Output
2 '\n' ''
9 '' ''
  • Some line readers also end a line at a CR. Java BufferedReader.readLine says: "A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), a carriage return followed immediately by a line feed, or by reaching the end-of-file (EOF)."12 .NET StreamReader.ReadLine says: "A line is defined as a sequence of characters followed by a line feed",13 a carriage return, or a CRLF. In Node.js, "The 'line' event is emitted whenever the input stream receives an end-of-line input",14 and an end-of-line input is LF, CR or CRLF. In a file that has a CR alone, these readers count more lines than awk or sed, so line N is a different line:
import { createInterface } from "node:readline";
import { Readable } from "node:stream";

const lines = [];
for await (const line of createInterface({ input: Readable.from(["a\rb\nc\n"]) })) {
  lines.push(line);
}
console.log(lines);
console.log("a\rb\nc\n".split("\n"));
Output
[ 'a', 'b', 'c' ]
[ 'a\rb', 'c', '' ]
  • Reading the whole file for one line. A solution that reads all the lines into memory needs memory for the whole file, also when N is 1. For a large file, read one line at a time and stop at line N, as all the solutions here do except the JavaScript solution.

Code

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

read_line.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

"""Reads one line of a text file by its number."""

from os import PathLike


def read_line(path: str | PathLike[str], number: int) -> str | None:
    """Returns line number of the UTF-8 file at path, or None if there is no such line.

    Line 1 is the first line. A line ends at LF, and the LF is not part of it.
    A last line with no LF is a line too. The function reads the file only up
    to the line. Raises FileNotFoundError if the file does not exist.
    """
    # 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:
        if number < 1:
            return None
        for n, line in enumerate(f, start=1):
            if n == number:
                return line.removesuffix("\n")
    return None
test_read_line.py 41 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

import pytest

from read_line import read_line

NUMBERS = "".join(f"{i}\n" for i in range(100000)).encode()

# name: (the bytes of the file, the line number, the result)
CASES = {
    "first": (b"a\nb\nc\n", 1, "a"),
    "middle": (b"a\nb\nc\n", 2, "b"),
    "last": (b"a\nb\nc\n", 3, "c"),
    "past-the-end": (b"a\nb\n", 3, None),
    "zero": (b"a\n", 0, None),
    "negative": (b"a\n", -1, None),
    "empty": (b"", 1, None),
    "empty-line": (b"a\n\nb\n", 2, ""),
    "only-newline": (b"\n", 1, ""),
    "no-final-newline": (b"a\nb", 2, "b"),
    "crlf": (b"a\r\nb\r\n", 1, "a\r"),
    "lone-cr": (b"a\rb\nc\n", 2, "c"),
    "non-ascii": ("caf\u00e9\nzo\u00eb\n".encode(), 2, "zo\u00eb"),
    # 100000 lines with the numbers 0 to 99999. Line n holds n - 1.
    "many-lines": (NUMBERS, 100000, "99999"),
    "many-lines-past-the-end": (NUMBERS, 100001, None),
}


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path, name):
    data, number, expect = CASES[name]
    path = tmp_path / "input.txt"
    path.write_bytes(data)
    assert read_line(path, number) == expect


def test_not_found(tmp_path):
    with pytest.raises(FileNotFoundError):
        read_line(tmp_path / "missing.txt", 1)
read_line.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

#include "read_line.hpp"

#include <fstream>

std::expected<std::optional<std::string>, LineError> read_line(const std::filesystem::path& path,
                                                               int number) {
    // 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(LineError::cannot_open);
    }
    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.
    for (int n = 1; n <= number && std::getline(in, line); n++) {
        if (n == number) {
            return line;
        }
    }
    if (in.bad()) {
        return std::unexpected(LineError::read_failed);
    }
    return std::nullopt;
}
read_line.hpp 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.
// since: C++23 (std::expected)

#pragma once

#include <expected>
#include <filesystem>
#include <optional>
#include <string>

enum class LineError { cannot_open, read_failed };

// Returns line number of the file at path, or std::nullopt if there is no
// such line. Line 1 is the first line. A line ends at LF, and the LF is not
// part of it. A last line with no LF is a line too. The function reads the
// file only up to the line.
std::expected<std::optional<std::string>, LineError> read_line(const std::filesystem::path& path,
                                                               int number);
test_read_line.cpp 74 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

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

#include "read_line.hpp"

namespace {

const std::filesystem::path input = "read_line_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()));
}

struct test_case {
    const char* name;
    std::string data;
    int number;
    std::optional<std::string> want;
};

}  // namespace

int main() {
    // 100000 lines with the numbers 0 to 99999. Line n holds n - 1.
    std::string numbers;
    for (int i = 0; i < 100000; i++) {
        numbers += std::to_string(i) + "\n";
    }

    const std::vector<test_case> cases = {
        {"first", "a\nb\nc\n", 1, "a"},
        {"middle", "a\nb\nc\n", 2, "b"},
        {"last", "a\nb\nc\n", 3, "c"},
        {"past-the-end", "a\nb\n", 3, std::nullopt},
        {"zero", "a\n", 0, std::nullopt},
        {"negative", "a\n", -1, std::nullopt},
        {"empty", "", 1, std::nullopt},
        {"empty-line", "a\n\nb\n", 2, ""},
        {"only-newline", "\n", 1, ""},
        {"no-final-newline", "a\nb", 2, "b"},
        {"crlf", "a\r\nb\r\n", 1, "a\r"},
        {"lone-cr", "a\rb\nc\n", 2, "c"},
        // U+00E9 is C3 A9, and U+00EB is C3 AB.
        {"non-ascii", "caf\xc3\xa9\nzo\xc3\xab\n", 2, "zo\xc3\xab"},
        {"many-lines", numbers, 100000, "99999"},
        {"many-lines-past-the-end", numbers, 100001, std::nullopt},
    };
    int failed = 0;
    for (const auto& c : cases) {
        write(c.data);
        auto got = read_line(input, c.number);
        if (!got || *got != c.want) {
            std::fprintf(stderr, "case %s failed\n", c.name);
            failed++;
        }
    }
    auto missing = read_line("no/such/dir/missing.txt", 1);
    if (missing || missing.error() != LineError::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;
}
SpecificLine.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;

/** Reads one line of a text file by its number. */
public final class SpecificLine {
  private SpecificLine() {}

  /**
   * Returns line number of the UTF-8 file at path, or an empty Optional if there is no such line.
   * Line 1 is the first line. A line ends at LF, and the LF is not part of it. A last line with no
   * LF is a line too. The method reads the file only up to the line.
   *
   * @throws java.nio.file.NoSuchFileException if the file does not exist
   */
  public static Optional<String> read(Path path, int number) throws IOException {
    // The method reads bytes, not BufferedReader.readLine, because readLine
    // also ends a line at a CR.
    try (InputStream in = new BufferedInputStream(Files.newInputStream(path))) {
      if (number < 1) {
        return Optional.empty();
      }
      ByteArrayOutputStream line = new ByteArrayOutputStream();
      int n = 1;
      int b;
      while ((b = in.read()) != -1) {
        if (b != '\n') {
          if (n == number) {
            line.write(b);
          }
        } else if (n == number) {
          return Optional.of(line.toString(StandardCharsets.UTF_8));
        } else {
          n++;
        }
      }
      // A last line with no LF ends at the end of the file.
      if (n == number && line.size() > 0) {
        return Optional.of(line.toString(StandardCharsets.UTF_8));
      }
      return Optional.empty();
    }
  }
}
SpecificLineTest.java 64 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-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.Optional;
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 SpecificLineTest {
  @TempDir Path dir;

  // 100000 lines with the numbers 0 to 99999. Line n holds n - 1.
  private static String numbers() {
    StringBuilder b = new StringBuilder();
    for (int i = 0; i < 100000; i++) {
      b.append(i).append('\n');
    }
    return b.toString();
  }

  static Stream<Arguments> cases() {
    String many = numbers();
    return Stream.of(
        Arguments.of("first", "a\nb\nc\n", 1, Optional.of("a")),
        Arguments.of("middle", "a\nb\nc\n", 2, Optional.of("b")),
        Arguments.of("last", "a\nb\nc\n", 3, Optional.of("c")),
        Arguments.of("past-the-end", "a\nb\n", 3, Optional.empty()),
        Arguments.of("zero", "a\n", 0, Optional.empty()),
        Arguments.of("negative", "a\n", -1, Optional.empty()),
        Arguments.of("empty", "", 1, Optional.empty()),
        Arguments.of("empty-line", "a\n\nb\n", 2, Optional.of("")),
        Arguments.of("only-newline", "\n", 1, Optional.of("")),
        Arguments.of("no-final-newline", "a\nb", 2, Optional.of("b")),
        Arguments.of("crlf", "a\r\nb\r\n", 1, Optional.of("a\r")),
        Arguments.of("lone-cr", "a\rb\nc\n", 2, Optional.of("c")),
        Arguments.of("non-ascii", "caf\u00e9\nzo\u00eb\n", 2, Optional.of("zo\u00eb")),
        Arguments.of("many-lines", many, 100000, Optional.of("99999")),
        Arguments.of("many-lines-past-the-end", many, 100001, Optional.empty()));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void read(String name, String text, int number, Optional<String> want) throws IOException {
    Path path = dir.resolve("input.txt");
    Files.writeString(path, text, StandardCharsets.UTF_8);
    assertEquals(want, SpecificLine.read(path, number), name);
  }

  @Test
  void notFound() {
    assertThrows(NoSuchFileException.class, () -> SpecificLine.read(dir.resolve("missing.txt"), 1));
  }
}
read_line.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

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

#include "read_line.h"

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

int read_line(const char *path, int number, char **line, size_t *len) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        return -1;
    }
    char *buf = NULL;
    size_t cap = 0;
    ssize_t n = -1;
    // getline reads up to and with the next LF, and grows buf as necessary.
    // It returns -1 at the end of the file, or on an error.
    for (int i = 0; i < number; i++) {
        n = getline(&buf, &cap, f);
        if (n < 0) {
            break;
        }
    }
    int failed = ferror(f);
    int e = errno;
    fclose(f);
    if (failed) {
        free(buf);
        errno = e;
        return -1;
    }
    if (number < 1 || n < 0) {
        free(buf);
        return 0;
    }
    if (n > 0 && buf[n - 1] == '\n') {
        buf[--n] = '\0';
    }
    *line = buf;
    *len = (size_t)n;
    return 1;
}
read_line.h 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

#ifndef READ_LINE_H
#define READ_LINE_H

#include <stddef.h>

// read_line reads line number of the file at path. Line 1 is the first line.
// A line ends at LF, and the LF is not part of it. A last line with no LF is a
// line too. It reads the file only up to the line.
//
// It returns 1 and puts the line into *line and its length into *len: the
// line is a new C string, which the caller frees. It returns 0 if there is no
// such line. It returns -1 and sets errno if it cannot read the file: ENOENT
// if the file does not exist.
int read_line(const char *path, int number, char **line, size_t *len);

#endif
test_read_line.c 79 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

#include "read_line.h"

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

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

// want is NULL if the case wants no line.
static void check(const char *name, const char *data, size_t size, int number, const char *want) {
    write_file(data, size);
    char *line = NULL;
    size_t len = 0;
    int got = read_line(path, number, &line, &len);
    if (got < 0) {
        fprintf(stderr, "case %s: error %d\n", name, errno);
        exit(1);
    }
    if (want == NULL ? got != 0 : got != 1 || len != strlen(want) || strcmp(line, want) != 0) {
        fprintf(stderr, "case %s: got %d \"%s\"\n", name, got, got == 1 ? line : "");
        exit(1);
    }
    free(line);
}

// sizeof counts the bytes of the literal, but not the final NUL.
#define CASE(name, data, number, want) check(name, data, sizeof(data) - 1, number, want)

int main(void) {
    CASE("first", "a\nb\nc\n", 1, "a");
    CASE("middle", "a\nb\nc\n", 2, "b");
    CASE("last", "a\nb\nc\n", 3, "c");
    CASE("past-the-end", "a\nb\n", 3, NULL);
    CASE("zero", "a\n", 0, NULL);
    CASE("negative", "a\n", -1, NULL);
    CASE("empty", "", 1, NULL);
    CASE("empty-line", "a\n\nb\n", 2, "");
    CASE("only-newline", "\n", 1, "");
    CASE("no-final-newline", "a\nb", 2, "b");
    CASE("crlf", "a\r\nb\r\n", 1, "a\r");
    CASE("lone-cr", "a\rb\nc\n", 2, "c");
    // U+00E9 is C3 A9, and U+00EB is C3 AB.
    CASE("non-ascii", "caf\xc3\xa9\nzo\xc3\xab\n", 2, "zo\xc3\xab");

    // 100000 lines with the numbers 0 to 99999. Line n holds n - 1.
    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, 100000, "99999");
    check("many-lines-past-the-end", data, size, 100001, NULL);
    free(data);

    char *line;
    size_t len;
    errno = 0;
    if (read_line("no/such/dir/missing.txt", 1, &line, &len) != -1 || errno != ENOENT) {
        fprintf(stderr, "case not-found: want -1 and ENOENT\n");
        return 1;
    }
    remove(path);
    puts("ok");
    return 0;
}
SpecificLine.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

using System.Text;

/// <summary>Reads one line of a text file by its number.</summary>
public static class SpecificLine
{
    /// <summary>
    /// Returns line number of the UTF-8 file at path, or null if there is no such line. Line 1 is
    /// the first line. A line ends at LF, and the LF is not part of it. A last line with no LF is
    /// a line too. The method reads the file only up to the line.
    /// </summary>
    /// <exception cref="FileNotFoundException">The file does not exist.</exception>
    public static string? Read(string path, int number)
    {
        // The method reads bytes, not StreamReader.ReadLine, because ReadLine
        // also ends a line at a CR.
        using var stream = new BufferedStream(File.OpenRead(path));
        if (number < 1)
        {
            return null;
        }
        var line = new MemoryStream();
        int n = 1;
        int b;
        while ((b = stream.ReadByte()) != -1)
        {
            if (b != '\n')
            {
                if (n == number)
                {
                    line.WriteByte((byte)b);
                }
            }
            else if (n == number)
            {
                return Encoding.UTF8.GetString(line.ToArray());
            }
            else
            {
                n++;
            }
        }
        // A last line with no LF ends at the end of the file.
        return n == number && line.Length > 0 ? Encoding.UTF8.GetString(line.ToArray()) : null;
    }
}
SpecificLineTests.cs 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

using System.Text;
using Xunit;

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

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

    // 100000 lines with the numbers 0 to 99999. Line n holds n - 1.
    private static string Numbers() =>
        string.Concat(Enumerable.Range(0, 100000).Select(i => $"{i}\n"));

    public static TheoryData<string, string, int, string?> Cases => new()
    {
        { "first", "a\nb\nc\n", 1, "a" },
        { "middle", "a\nb\nc\n", 2, "b" },
        { "last", "a\nb\nc\n", 3, "c" },
        { "past-the-end", "a\nb\n", 3, null },
        { "zero", "a\n", 0, null },
        { "negative", "a\n", -1, null },
        { "empty", "", 1, null },
        { "empty-line", "a\n\nb\n", 2, "" },
        { "only-newline", "\n", 1, "" },
        { "no-final-newline", "a\nb", 2, "b" },
        { "crlf", "a\r\nb\r\n", 1, "a\r" },
        { "lone-cr", "a\rb\nc\n", 2, "c" },
        { "non-ascii", "caf\u00e9\nzo\u00eb\n", 2, "zo\u00eb" },
        { "many-lines", Numbers(), 100000, "99999" },
        { "many-lines-past-the-end", Numbers(), 100001, null },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Read(string name, string text, int number, string? want)
    {
        string path = Path.Combine(dir, "input.txt");
        // UTF8Encoding(false) writes no byte order mark.
        File.WriteAllText(path, text, new UTF8Encoding(false));
        Assert.Equal(want, SpecificLine.Read(path, number));
        _ = name;
    }

    [Fact]
    public void NotFound()
    {
        Assert.Throws<FileNotFoundException>(() => SpecificLine.Read(Path.Combine(dir, "missing.txt"), 1));
    }
}
readLine.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

import { readFileSync } from "node:fs";

// Returns line number of the UTF-8 file at path, or null if there is no such
// line. Line 1 is the first line. 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 readLine(path, number) {
  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();
  // Line numbers start at 1, and indexes start at 0.
  if (!Number.isInteger(number) || number < 1 || number > lines.length) return null;
  return lines[number - 1];
}
readLine.test.js 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-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 { readLine } from "./readLine.js";

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

const numbers = Array.from({ length: 100000 }, (_, i) => `${i}\n`).join("");

// [name, the text of the file, the line number, the result]
const cases = [
  ["first", "a\nb\nc\n", 1, "a"],
  ["middle", "a\nb\nc\n", 2, "b"],
  ["last", "a\nb\nc\n", 3, "c"],
  ["past-the-end", "a\nb\n", 3, null],
  ["zero", "a\n", 0, null],
  ["negative", "a\n", -1, null],
  ["empty", "", 1, null],
  ["empty-line", "a\n\nb\n", 2, ""],
  ["only-newline", "\n", 1, ""],
  ["no-final-newline", "a\nb", 2, "b"],
  ["crlf", "a\r\nb\r\n", 1, "a\r"],
  ["lone-cr", "a\rb\nc\n", 2, "c"],
  ["non-ascii", "caf\u00e9\nzo\u00eb\n", 2, "zo\u00eb"],
  // 100000 lines with the numbers 0 to 99999. Line n holds n - 1.
  ["many-lines", numbers, 100000, "99999"],
  ["many-lines-past-the-end", numbers, 100001, null],
];

for (const [name, text, number, want] of cases) {
  test(name, () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, text, "utf8");
    assert.equal(readLine(path, number), want);
  });
}

test("not-found", () => {
  assert.throws(() => readLine(join(dir, "missing.txt"), 1), { code: "ENOENT" });
});
readLine.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

import { readFileSync } from "node:fs";

// Returns line number of the UTF-8 file at path, or null if there is no such
// line. Line 1 is the first line. 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 readLine(path: string, number: number): string | null {
  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();
  // Line numbers start at 1, and indexes start at 0.
  if (!Number.isInteger(number) || number < 1 || number > lines.length) return null;
  return lines[number - 1];
}
readLine.test.ts 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-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 { readLine } from "./readLine.ts";

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

const numbers = Array.from({ length: 100000 }, (_, i) => `${i}\n`).join("");

// [name, the text of the file, the line number, the result]
const cases: [string, string, number, string | null][] = [
  ["first", "a\nb\nc\n", 1, "a"],
  ["middle", "a\nb\nc\n", 2, "b"],
  ["last", "a\nb\nc\n", 3, "c"],
  ["past-the-end", "a\nb\n", 3, null],
  ["zero", "a\n", 0, null],
  ["negative", "a\n", -1, null],
  ["empty", "", 1, null],
  ["empty-line", "a\n\nb\n", 2, ""],
  ["only-newline", "\n", 1, ""],
  ["no-final-newline", "a\nb", 2, "b"],
  ["crlf", "a\r\nb\r\n", 1, "a\r"],
  ["lone-cr", "a\rb\nc\n", 2, "c"],
  ["non-ascii", "caf\u00e9\nzo\u00eb\n", 2, "zo\u00eb"],
  // 100000 lines with the numbers 0 to 99999. Line n holds n - 1.
  ["many-lines", numbers, 100000, "99999"],
  ["many-lines-past-the-end", numbers, 100001, null],
];

for (const [name, text, number, want] of cases) {
  test(name, () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, text, "utf8");
    assert.equal(readLine(path, number), want);
  });
}

test("not-found", () => {
  assert.throws(() => readLine(join(dir, "missing.txt"), 1), { code: "ENOENT" });
});
read_line.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

// Package specificline reads one line of a text file by its number.
package specificline

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

// ReadLine returns line number of the UTF-8 file at path, and true. If there
// is no such line, it returns "" and false. Line 1 is the first line. A line
// ends at LF, and the LF is not part of it. A last line with no LF is a line
// too. The function reads the file only up to the line. A missing file gives
// an error that matches fs.ErrNotExist.
func ReadLine(path string, number int) (string, bool, error) {
	f, err := os.Open(path)
	if err != nil {
		return "", false, err
	}
	defer f.Close()
	if number < 1 {
		return "", false, nil
	}
	// bufio.Reader, not bufio.Scanner: ScanLines removes a CR before the LF,
	// and a Scanner has a limit on the length of a line.
	r := bufio.NewReader(f)
	for n := 1; ; n++ {
		// 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 "", false, err
		}
		if line == "" {
			return "", false, nil
		}
		if n == number {
			return strings.TrimSuffix(line, "\n"), true, nil
		}
		if err != nil {
			return "", false, nil
		}
	}
}
read_line_test.go 72 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

package specificline

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

// numbers returns 100000 lines with the numbers 0 to 99999. Line n holds
// n - 1.
func numbers() string {
	var b strings.Builder
	for i := 0; i < 100000; i++ {
		b.WriteString(strconv.Itoa(i) + "\n")
	}
	return b.String()
}

func TestReadLine(t *testing.T) {
	many := numbers()
	cases := []struct {
		name, text string
		number     int
		want       string
		ok         bool
	}{
		{"first", "a\nb\nc\n", 1, "a", true},
		{"middle", "a\nb\nc\n", 2, "b", true},
		{"last", "a\nb\nc\n", 3, "c", true},
		{"past-the-end", "a\nb\n", 3, "", false},
		{"zero", "a\n", 0, "", false},
		{"negative", "a\n", -1, "", false},
		{"empty", "", 1, "", false},
		{"empty-line", "a\n\nb\n", 2, "", true},
		{"only-newline", "\n", 1, "", true},
		{"no-final-newline", "a\nb", 2, "b", true},
		{"crlf", "a\r\nb\r\n", 1, "a\r", true},
		{"lone-cr", "a\rb\nc\n", 2, "c", true},
		{"non-ascii", "caf\u00e9\nzo\u00eb\n", 2, "zo\u00eb", true},
		{"many-lines", many, 100000, "99999", true},
		{"many-lines-past-the-end", many, 100001, "", false},
	}
	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)
			}
			got, ok, err := ReadLine(path, c.number)
			if err != nil {
				t.Fatal(err)
			}
			if got != c.want || ok != c.ok {
				t.Errorf("got %q, %v, want %q, %v", got, ok, c.want, c.ok)
			}
		})
	}
}

func TestNotFound(t *testing.T) {
	_, _, err := ReadLine(filepath.Join(t.TempDir(), "missing.txt"), 1)
	if !errors.Is(err, fs.ErrNotExist) {
		t.Errorf("got %v, want fs.ErrNotExist", err)
	}
}
read_line.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

//! Reads one line of a text file by its number.

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

/// Returns line `number` of the UTF-8 file at `path`, or `None` if there is
/// no such line.
///
/// Line 1 is the first line. A line ends at LF, and the LF is not part of it.
/// A last line with no LF is a line too. The function reads the file only up
/// to the line. A missing file gives an error of kind `NotFound`.
pub fn read_line(path: impl AsRef<Path>, number: i32) -> io::Result<Option<String>> {
    let mut reader = BufReader::new(File::open(path)?);
    if number < 1 {
        return Ok(None);
    }
    // read_line, not lines: lines also removes a CR before the LF.
    let mut line = String::new();
    for _ in 0..number {
        line.clear();
        // read_line reads up to and with the next LF. It returns 0 at the
        // end of the file.
        if reader.read_line(&mut line)? == 0 {
            return Ok(None);
        }
    }
    if line.ends_with('\n') {
        line.pop();
    }
    Ok(Some(line))
}
tests/read_line_test.rs 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

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

use algo_read_line::read_line;

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

#[test]
fn cases() {
    // 100000 lines with the numbers 0 to 99999. Line n holds n - 1.
    let numbers: String = (0..100000).map(|i| format!("{i}\n")).collect();
    let cases: &[(&str, &str, i32, Option<&str>)] = &[
        ("first", "a\nb\nc\n", 1, Some("a")),
        ("middle", "a\nb\nc\n", 2, Some("b")),
        ("last", "a\nb\nc\n", 3, Some("c")),
        ("past-the-end", "a\nb\n", 3, None),
        ("zero", "a\n", 0, None),
        ("negative", "a\n", -1, None),
        ("empty", "", 1, None),
        ("empty-line", "a\n\nb\n", 2, Some("")),
        ("only-newline", "\n", 1, Some("")),
        ("no-final-newline", "a\nb", 2, Some("b")),
        ("crlf", "a\r\nb\r\n", 1, Some("a\r")),
        ("lone-cr", "a\rb\nc\n", 2, Some("c")),
        ("non-ascii", "caf\u{e9}\nzo\u{eb}\n", 2, Some("zo\u{eb}")),
        ("many-lines", &numbers, 100000, Some("99999")),
        ("many-lines-past-the-end", &numbers, 100001, None),
    ];
    for (name, text, number, want) in cases {
        let path = temp_file(name, text);
        let got = read_line(&path, *number).unwrap();
        assert_eq!(got.as_deref(), *want, "case {name}");
        fs::remove_file(path).unwrap();
    }
}

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

# read_line PATH NUMBER
# Prints line NUMBER of the file at PATH with an LF after it. Line 1 is the
# first line. Returns 0 if the line is there, 1 if there is no such line, and
# 2 if the file cannot be read.
read_line() {
  [[ -r $1 && ! -d $1 ]] || { printf 'read_line: cannot read %s\n' "$1" >&2; return 2; }
  # NR is the number of the current line. exit stops the read at the line,
  # and the END action gives the status. The file comes on standard input,
  # so awk does not take a name such as x=1 as an assignment.
  awk -v n="$2" 'NR == n { print; found = 1; exit } END { exit !found }' <"$1"
}
test_read_line.bats 50 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-specific-line-from-a-file/.

bats_require_minimum_version 1.5.0

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

check() { # check BYTES NUMBER WANT
  printf '%b' "$1" >"$file"
  # The x keeps the final LF, which $(...) removes.
  got=$(read_line "$file" "$2" && printf x)
  [ "$got" = "$(printf '%bx' "$3")" ]
}

check_none() { # check_none BYTES NUMBER
  printf '%b' "$1" >"$file"
  run read_line "$file" "$2"
  [ "$status" -eq 1 ] && [ "$output" = "" ]
}

@test "first" { check 'a\nb\nc\n' 1 'a\n'; }
@test "middle" { check 'a\nb\nc\n' 2 'b\n'; }
@test "last" { check 'a\nb\nc\n' 3 'c\n'; }
@test "past-the-end" { check_none 'a\nb\n' 3; }
@test "zero" { check_none 'a\n' 0; }
@test "negative" { check_none 'a\n' -1; }
@test "empty" { check_none '' 1; }
@test "empty-line" { check 'a\n\nb\n' 2 '\n'; }
@test "only-newline" { check '\n' 1 '\n'; }
@test "no-final-newline" { check 'a\nb' 2 'b\n'; }
@test "crlf" { check 'a\r\nb\r\n' 1 'a\r\n'; }
@test "lone-cr" { check 'a\rb\nc\n' 2 'c\n'; }
@test "non-ascii" { check 'caf\xc3\xa9\nzo\xc3\xab\n' 2 'zo\xc3\xab\n'; }

@test "many-lines" {
  seq 0 99999 >"$file"
  [ "$(read_line "$file" 100000)" = "99999" ]
  run read_line "$file" 100001
  [ "$status" -eq 1 ]
}

@test "not-found" {
  run read_line "$BATS_TEST_TMPDIR/missing.txt" 1
  [ "$status" -eq 2 ]
  [ "$output" = "read_line: cannot read $BATS_TEST_TMPDIR/missing.txt" ]
}

References

  1. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), awk, OPERANDS; Variables and Special Variables (NR); Actions (exit)
  2. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), Base Definitions, Chapter 3, Definitions, 3.172 Incomplete Line; 3.185 Line
  3. The Python Standard Library, Built-in Functions, open (newline)
  4. MDN Web Docs, String.prototype.split(), Description
  5. .NET API reference, Stream.ReadByte
  6. Go standard library, package bufio, Reader.ReadString; ScanLines
  7. The Rust Standard Library, std::io::BufRead, read_line; lines
  8. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), getdelim, getline, DESCRIPTION; RETURN VALUE
  9. cppreference.com, std::getline
  10. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), head, OPTIONS (-n)
  11. The Python Standard Library, linecache, getline
  12. Java SE 25 API, java.io.BufferedReader, readLine
  13. .NET API reference, StreamReader.ReadLine, Remarks
  14. Node.js documentation, Readline, Event: 'line'

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