Programming Search⌘K

Taskcore

Remove lines from a file

Also called delete lines from a file, delete line N of a file, sed Nd, remove a range of lines from a file.

Remove count lines from a file, from line start, by writing the rest to a new file in the same directory and renaming it over the old one, so a reader never sees a part of a file.

Task

Remove lines from a file. Rosetta Code states the task like this: "Remove a specific line or a number of lines from a file." The function "takes three parameters (filename, starting line, and the number of lines to be removed)".1 Line 1 is the first line. The function removes the lines, writes the rest of the file back under the same name, and returns the number of lines that it removed.

The task needs rules for what a line is and for what to do at the end of the file. This page uses these rules:

  • A line ends at LF, and the LF goes with the line. When a line goes, its LF goes too. A CR is a byte like the others, so a line that ends in CRLF loses its CR and its LF. The other bytes of the file do not change.
  • A last line with no LF is a line too. If the function removes it, the file then ends with the LF of the line before it. If the function removes an earlier line, the last line still has no LF.
  • An empty line is a line. Rosetta Code says: "Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed."1
  • The file can end before the range ends. Rosetta Code says: "An appropriate message should appear if an attempt is made to remove lines beyond the end of the file."1 Here the function returns the number of lines that it removed, and the caller shows the message if that number is less than the count. If the function removes no line, it does not write the file.
  • A bad range is an error. A start less than 1 or a count less than 0 is an error, and the function checks the range before it opens the file. A count of 0 is not an error: the function removes no line.

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

Solutions

The method is the same in each language:

  1. Read the file and count the lines. Copy each line that is not in the range to a new file in the same directory as the old file.
  2. If no line was in the range, delete the new file and return 0. The old file does not change.
  3. Give the new file the permissions of the old file, and write its data to the disk.
  4. Rename the new file to the name of the old file.

The rename is the step that changes the file. POSIX says that during a rename, a directory entry named new "shall remain visible to other threads throughout the renaming operation and refer either to the file referred to by new or old before the operation began."2 So a program that opens the file gets the old file or the new file, and never a part of a file. If the program stops before the rename, the old file does not change. Before the rename, fsync "shall request that all data for the open file descriptor named by fildes is to be transferred to the storage device".3 Without this step, the new name can refer to data that is not yet on the disk.

Python, Go, Rust, C, C++ and Bash read the file one line at a time, so they need memory for one line only. JavaScript, Java and C# read the whole file into an array of bytes and keep the bytes before and after the range. This needs less code, but it needs memory for the whole file.

  • Python. The file is open in binary mode, so only LF ends a line and the bytes do not change. enumerate(src, start=1) gives each line with its number. tempfile.mkstemp(dir=...) makes the new file in the same directory. shutil.copymode does this: "Copy the permission bits from src to dst".4 os.fsync writes the data to the disk, and os.replace renames the file: "If dst exists and is a file, it will be replaced silently if the user has permission."5 A bad range raises ValueError.
  • JavaScript and TypeScript (Node.js). readFileSync gives a Buffer, and indexOf(10, offset) finds the next LF. The code skips start - 1 lines, then skips count lines, and keeps the bytes before and after the lines that it skipped the second time. openSync(tmp, 'wx', 0o600) makes the new file. The flag 'wx' is "Like 'w' but fails if the path exists",6 so the code does not write over a file that has the same name. fsyncSync writes the data to the disk, chmodSync copies the permissions, and renameSync renames the file: "In the case that newPath already exists, it will be overwritten."6 A bad range throws a RangeError. The TypeScript file adds types only.
  • Java. Files.readAllBytes reads the file, and a loop finds each LF. Files.createTempFile(dir, prefix, suffix) "Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name."7 A FileOutputStream writes the bytes, and getFD().sync() writes them to the disk. If the file system has POSIX permissions, setPosixFilePermissions copies them. Files.move with ATOMIC_MOVE renames the file. A bad range throws an IllegalArgumentException.
  • C#. File.ReadAllBytes reads the file, and Array.IndexOf finds each LF. A FileStream with FileMode.CreateNew makes the new file, and Flush(true) writes the data to the disk. On Unix, File.SetUnixFileMode "Sets the specified UnixFileMode of the file on the specified path."8 Then File.Move(tmp, path, overwrite: true) renames the file. The documentation describes the parameter overwrite set to true, "which replaces the file if it exists".9 A bad range throws an ArgumentOutOfRangeException.
  • Go. bufio.Reader.ReadBytes('\n') reads each line with its LF, also a line that is longer than the buffer. os.CreateTemp "creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting file."10 A bufio.Writer writes the lines. Chmod copies the permissions, and Sync "commits the current contents of the file to stable storage."10 os.Rename renames the file: "If newpath already exists and is not a directory, Rename replaces it."10 A deferred function closes and removes the new file on each return before the rename. A bad range gives an error that wraps ErrBadRange.
  • Rust. BufRead::read_until(b'\n', ...) reads each line with its LF into a Vec<u8>. The new file opens with create_new, which "Sets the option to create a new file, failing if it already exists."11 Its name has the process ID and a counter, and the code tries the next name if a file has that name. set_permissions copies the permissions, sync_all writes the data to the disk, and fs::rename renames the file, "replacing the original file if to already exists".12 Line numbers are u64 values, so they do not overflow. A bad range gives an error of kind InvalidInput.
  • C. mkstemp makes the new file from the path and the suffix .XXXXXX. POSIX says that it shall "create a regular file with a unique name derived from template and return a file descriptor for the file open for reading and writing."13 A getc loop copies the bytes that are not in the range, and counts the lines in a long long. fchmod copies the permissions, fsync writes the data to the disk, and rename renames the file. remove_lines returns the number of lines that it removed, or -1 with errno set. A bad range sets errno to EINVAL.
  • C++. std::getline reads a binary std::ifstream one line at a time and removes the LF. The code writes each line that it keeps, and then an LF, except after a last line with no LF. The new file has a random suffix and opens with std::ios::noreplace (C++23), which means "open in exclusive mode".14 fs::permissions copies the permissions, and fs::rename renames the file "as if by the POSIX rename".15 This solution uses only the standard library, so it does not write the data to the disk before the rename. The result is a std::expected<int, RemoveError>.
  • Bash. awk 'END { print NR }' counts the lines. In the tests, it also counts a last line with no LF. The function then calculates how many lines it can remove. If that number is 0, it prints 0 and does not write the file. If not, mktemp makes the new file from the template $file.XXXXXX, and cp -p copies the old file with its permissions to the new file. Then the redirection > truncates the copy, head -n writes the lines before the range, and tail -n +K writes the lines from line K, the first line after the range. For tail, "The origin for counting shall be 1; that is, -n +1 represents the first line of the file".16 mv -f renames the new file. The function prints the number of lines that it removed, and returns 2 with a message on an error. It does not write the data to the disk before the rename.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl. For each case, fixtures/NAME.txt is the file before the call, and fixtures/NAME.after.txt is the file after the call.

  • first-two, middle and last: from a, b, c, d, lines 1 and 2 go and c, d stay, or lines 2 and 3 go and a, d stay. From a, b, c, line 3 goes and a, b stay.
  • past-the-end: line 3 of a file with two lines. The result is 0, and the file does not change.
  • partly-past-the-end: 5 lines from line 2 of a, b, c. The result is 2, and a stays.
  • count-zero: a count of 0. The result is 0, and the file does not change.
  • all-lines: lines 1 and 2 of a file with two lines. The result is 2, and the file is empty.
  • empty: line 1 of an empty file. The result is 0.
  • empty-line: line 2 of a, empty, b is the empty line, and it goes.
  • no-final-newline and remove-incomplete-line: the file is a, b with no LF at the end. If line 1 goes, b stays with no LF. If line 2 goes, the file is a and an LF.
  • crlf: line 2 of a CRLF, b CRLF, c CRLF goes with its CR and its LF.
  • lone-cr: line 1 of a CR b LF c LF is a CR b, because the CR does not end a line. After the call, the file is c and an LF.
  • non-ascii: line 2 of café, naïve, zoë goes.
  • large-count: 2147483647 lines from line 2 of a file with two lines. The result is 1.

The tests also write a file of 100000 lines with the numbers 0 to 99999, and remove 99998 lines from line 2. After the call, the file has the lines 0 and 99999. Other tests check that a file with mode 640 keeps its mode, and that no new file stays in the directory. The cases in cases/errors.jsonl must give the error not-found or bad-range, and must not change a file. The toolchain does not load that file yet, so each test file holds the cases by name.

Pitfalls

  • Redirecting the output to the input file empties the file. In sed '2d' notes.txt > notes.txt, the shell does the redirection before it runs sed.17 For >, the shell opens an existing file as if open "was called with the O_TRUNC flag set".17 So the file is empty before sed reads it. Write the output to a new file, and then rename the new file:
dir=$(mktemp -d)
printf 'a\nb\nc\n' >"$dir/notes.txt"
# Wrong: the shell empties notes.txt before sed reads it.
sed '2d' "$dir/notes.txt" >"$dir/notes.txt"
[ -s "$dir/notes.txt" ] || echo 'notes.txt is empty'
printf 'a\nb\nc\n' >"$dir/notes.txt"
# Right: write to a new file, then rename it.
sed '2d' "$dir/notes.txt" >"$dir/notes.new" && mv "$dir/notes.new" "$dir/notes.txt"
cat "$dir/notes.txt"
rm -r "$dir"
Output
notes.txt is empty
a
c
  • sed -i is not portable. The POSIX synopsis of sed is sed [-En] script [file...], with no -i option.18 In FreeBSD sed, -i takes an argument, extension. The -I option edits files in place, "saving backups with the specified extension", and -i works "similarly to -I".19 So FreeBSD sed -i '2d' notes.txt takes 2d as the extension and notes.txt as the script. A portable script writes to a new file and renames it, as the Bash solution does.
  • The new file does not have the permissions of the old file. POSIX mkstemp opens the file as if with open(pathname, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR),13 and in Python, the file from mkstemp "is readable and writable only by the creating user ID."20 If the code renames the new file and does not copy the permissions, a file with mode 644 has mode 600 after the call:
import os
import stat
import tempfile

with tempfile.TemporaryDirectory() as directory:
    path = os.path.join(directory, 'notes.txt')
    with open(path, 'w') as f:
        f.write('a\nb\nc\n')
    os.chmod(path, 0o644)
    print('before:', oct(stat.S_IMODE(os.stat(path).st_mode)))
    fd, tmp = tempfile.mkstemp(dir=directory)
    with os.fdopen(fd, 'w') as f:
        f.write('a\nc\n')
    # No shutil.copymode(path, tmp) here.
    os.replace(tmp, path)
    print('after: ', oct(stat.S_IMODE(os.stat(path).st_mode)))
Output
before: 0o644
after:  0o600
  • The new file must be on the same file system. A temp directory such as /tmp can be on a different file system from the old file. Then POSIX rename can fail with [EXDEV], because the two files "are on different file systems and the implementation does not support hard links between file systems."2 Rust says about fs::rename: "This will not work if the new name is on a different mount point."12 Make the new file in the directory of the old file, as all the solutions here do.
  • split('\n') counts one line too many. If the text ends with an LF, split gives an empty string as the last part: "an empty (i.e., zero length) string appearing at the first (or last) position of the returned array."21 Code that removes lines with splice and puts the rest back together with join thus sees one more line than the file has. If the range starts just after the last line, the code removes the empty string, reports 1 line, and the file loses its last LF:
// Removes count lines from text, from line start, with split and join.
function removeLines(text, start, count) {
  const lines = text.split('\n');
  const removed = lines.splice(start - 1, count);
  return { text: lines.join('\n'), removed: removed.length };
}

// Two lines, and line 2 goes: the result is right.
console.log(JSON.stringify(removeLines('a\nb\n', 2, 1)));
// Two lines, and line 3 does not exist: the LF at the end goes.
console.log(JSON.stringify(removeLines('a\nb\n', 3, 1)));
Output
{"text":"a\n","removed":1}
{"text":"a\nb","removed":1}
  • start + count can be too large for an int. In the large-count case, start is 2 and count is 2147483647, so start + count does not fit in a 32-bit signed integer. The solutions in languages with fixed-size integers do not calculate start + count. They compare n - start < count, or they count the lines that they removed.
  • head -n 0 is not portable. For head, "The application shall ensure that the number option-argument is a positive decimal integer."22 So when start is 1, the Bash solution does not run head.
  • An atomic move can fail if the target exists. For ATOMIC_MOVE, Java says: "If the target file exists then it is implementation specific if the existing file is replaced or this method fails by throwing an IOException".7 On such a system, the Java solution throws the exception, deletes the new file and does not change the old file.

Code

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

remove_lines.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/remove-lines-from-a-file/.

"""Removes lines from a file and writes the rest back under the same name."""

import os
import shutil
import tempfile
from os import PathLike


def remove_lines(path: str | PathLike[str], start: int, count: int) -> int:
    """Removes count lines from the file at path, from line start, and returns how many it removed.

    Line 1 is the first line. A line ends at LF, and the LF goes with the line.
    The function returns less than count if the file ends first. If it removes
    no line, it does not write the file. Otherwise it writes the rest of the
    file to a new file in the same directory, and os.replace puts the new file
    in the place of the old one. Raises ValueError if start is less than 1 or
    count is less than 0, and FileNotFoundError if the file does not exist.
    """
    if start < 1 or count < 0:
        raise ValueError(f"bad range: start {start}, count {count}")
    path = os.fspath(path)
    directory, name = os.path.split(path)
    # Binary mode: only LF ends a line, and the bytes do not change.
    with open(path, "rb") as src:
        fd, tmp = tempfile.mkstemp(prefix=f".{name}.", suffix=".tmp", dir=directory or ".")
        try:
            removed = 0
            with os.fdopen(fd, "wb") as dst:
                for number, line in enumerate(src, start=1):
                    if start <= number < start + count:
                        removed += 1
                    else:
                        dst.write(line)
                if removed > 0:
                    dst.flush()
                    os.fsync(dst.fileno())
            if removed == 0:
                os.remove(tmp)
                return 0
            # mkstemp makes the file readable and writable only by its owner.
            shutil.copymode(path, tmp)
            os.replace(tmp, path)
            return removed
        except BaseException:
            if os.path.exists(tmp):
                os.remove(tmp)
            raise
test_remove_lines.py 74 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/remove-lines-from-a-file/.

import os
import stat

import pytest

from remove_lines import remove_lines

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

# name: (the bytes of the file, start, count, the result, the bytes after)
CASES = {
    "first-two": (b"a\nb\nc\nd\n", 1, 2, 2, b"c\nd\n"),
    "middle": (b"a\nb\nc\nd\n", 2, 2, 2, b"a\nd\n"),
    "last": (b"a\nb\nc\n", 3, 1, 1, b"a\nb\n"),
    "past-the-end": (b"a\nb\n", 3, 1, 0, b"a\nb\n"),
    "partly-past-the-end": (b"a\nb\nc\n", 2, 5, 2, b"a\n"),
    "count-zero": (b"a\nb\n", 1, 0, 0, b"a\nb\n"),
    "all-lines": (b"a\nb\n", 1, 2, 2, b""),
    "empty": (b"", 1, 1, 0, b""),
    "empty-line": (b"a\n\nb\n", 2, 1, 1, b"a\nb\n"),
    "no-final-newline": (b"a\nb", 1, 1, 1, b"b"),
    "remove-incomplete-line": (b"a\nb", 2, 1, 1, b"a\n"),
    "crlf": (b"a\r\nb\r\nc\r\n", 2, 1, 1, b"a\r\nc\r\n"),
    "lone-cr": (b"a\rb\nc\n", 1, 1, 1, b"c\n"),
    "non-ascii": ("caf\u00e9\nna\u00efve\nzo\u00eb\n".encode(), 2, 1, 1, "caf\u00e9\nzo\u00eb\n".encode()),
    "large-count": (b"a\nb\n", 2, 2147483647, 1, b"a\n"),
    # 100000 lines with the numbers 0 to 99999. Lines 2 to 99999 go.
    "many-lines": (NUMBERS, 2, 99998, 99998, b"0\n99999\n"),
}


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path, name):
    data, start, count, expect, after = CASES[name]
    path = tmp_path / "input.txt"
    path.write_bytes(data)
    assert remove_lines(path, start, count) == expect
    assert path.read_bytes() == after
    # No temporary file stays in the directory.
    assert os.listdir(tmp_path) == ["input.txt"]


def test_no_change_keeps_the_file(tmp_path):
    path = tmp_path / "input.txt"
    path.write_bytes(b"a\n")
    before = os.stat(path).st_ino
    assert remove_lines(path, 2, 1) == 0
    assert os.stat(path).st_ino == before


@pytest.mark.skipif(os.name != "posix", reason="POSIX permission bits")
def test_keeps_the_permissions(tmp_path):
    path = tmp_path / "input.txt"
    path.write_bytes(b"a\nb\n")
    os.chmod(path, 0o640)
    assert remove_lines(path, 1, 1) == 1
    assert stat.S_IMODE(os.stat(path).st_mode) == 0o640


def test_not_found(tmp_path):
    with pytest.raises(FileNotFoundError):
        remove_lines(tmp_path / "missing.txt", 1, 1)


@pytest.mark.parametrize("start, count", [(0, 1), (1, -1)])
def test_bad_range(tmp_path, start, count):
    path = tmp_path / "input.txt"
    path.write_bytes(b"a\nb\n")
    with pytest.raises(ValueError):
        remove_lines(path, start, count)
    assert path.read_bytes() == b"a\nb\n"
remove_lines.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

#include "remove_lines.hpp"

#include <fstream>
#include <random>
#include <string>
#include <system_error>

namespace fs = std::filesystem;

std::expected<int, RemoveError> remove_lines(const fs::path& path, int start, int count) {
    if (start < 1 || count < 0) {
        return std::unexpected(RemoveError::bad_range);
    }
    // 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(RemoveError::cannot_open);
    }
    std::error_code ec;
    const fs::perms perms = fs::status(path, ec).permissions();
    if (ec) {
        return std::unexpected(RemoveError::cannot_open);
    }
    // The new file is next to path, with a random suffix. noreplace (C++23)
    // makes the open fail if a file with that name exists.
    std::random_device random;
    fs::path tmp;
    std::ofstream out;
    for (int tries = 0; tries < 100 && !out.is_open(); tries++) {
        tmp = path;
        tmp += "." + std::to_string(random()) + ".tmp";
        out.open(tmp, std::ios::binary | std::ios::out | std::ios::noreplace);
    }
    if (!out.is_open()) {
        return std::unexpected(RemoveError::write_failed);
    }
    auto fail = [&](RemoveError e) {
        out.close();
        fs::remove(tmp, ec);
        return std::unexpected(e);
    };
    int removed = 0;
    std::string line;
    // getline removes the LF. If it stops at the end of the file, eof() is
    // true, and the line had no LF.
    for (long long n = 1; std::getline(in, line); n++) {
        if (n >= start && n - start < count) {
            removed++;
            continue;
        }
        out << line;
        if (!in.eof()) {
            out << '\n';
        }
    }
    if (in.bad()) {
        return fail(RemoveError::read_failed);
    }
    if (removed == 0) {
        out.close();
        fs::remove(tmp, ec);
        return 0;
    }
    out.close();
    if (!out) {
        return fail(RemoveError::write_failed);
    }
    fs::permissions(tmp, perms, ec);
    if (ec) {
        return fail(RemoveError::write_failed);
    }
    fs::rename(tmp, path, ec);
    if (ec) {
        return fail(RemoveError::write_failed);
    }
    return removed;
}
remove_lines.hpp 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

#pragma once

#include <expected>
#include <filesystem>

enum class RemoveError { bad_range, cannot_open, read_failed, write_failed };

// Removes count lines from the file at path, from line start, and returns how
// many it removed. Line 1 is the first line. A line ends at LF, and the LF
// goes with the line. The result is less than count if the file ends first.
// If no line goes, the file is not written. Otherwise the rest of the file
// goes to a new file in the same directory, and std::filesystem::rename puts
// it in the place of the old one. bad_range is the error when start is less
// than 1 or count is less than 0.
std::expected<int, RemoveError> remove_lines(const std::filesystem::path& path, int start,
                                             int count);
test_remove_lines.cpp 103 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

#include "remove_lines.hpp"

#include <climits>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

namespace fs = std::filesystem;

namespace {

int failures = 0;

void check(bool ok, const std::string& name, const char* what) {
    if (!ok) {
        std::cerr << "FAIL " << name << ": " << what << '\n';
        failures++;
    }
}

void write_file(const fs::path& path, const std::string& text) {
    std::ofstream(path, std::ios::binary) << text;
}

std::string read_file(const fs::path& path) {
    std::ifstream in(path, std::ios::binary);
    return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
}

struct Case {
    std::string name, text;
    int start, count, want;
    std::string after;
};

}  // namespace

int main() {
    const fs::path dir = fs::temp_directory_path() / "remove-lines-cpp-test";
    fs::remove_all(dir);
    fs::create_directory(dir);
    const fs::path path = dir / "input.txt";

    std::string many;
    for (int i = 0; i < 100000; i++) {
        many += std::to_string(i) + "\n";
    }
    const std::vector<Case> cases = {
        {"first-two", "a\nb\nc\nd\n", 1, 2, 2, "c\nd\n"},
        {"middle", "a\nb\nc\nd\n", 2, 2, 2, "a\nd\n"},
        {"last", "a\nb\nc\n", 3, 1, 1, "a\nb\n"},
        {"past-the-end", "a\nb\n", 3, 1, 0, "a\nb\n"},
        {"partly-past-the-end", "a\nb\nc\n", 2, 5, 2, "a\n"},
        {"count-zero", "a\nb\n", 1, 0, 0, "a\nb\n"},
        {"all-lines", "a\nb\n", 1, 2, 2, ""},
        {"empty", "", 1, 1, 0, ""},
        {"empty-line", "a\n\nb\n", 2, 1, 1, "a\nb\n"},
        {"no-final-newline", "a\nb", 1, 1, 1, "b"},
        {"remove-incomplete-line", "a\nb", 2, 1, 1, "a\n"},
        {"crlf", "a\r\nb\r\nc\r\n", 2, 1, 1, "a\r\nc\r\n"},
        {"lone-cr", "a\rb\nc\n", 1, 1, 1, "c\n"},
        {"non-ascii", "caf\xc3\xa9\nna\xc3\xafve\nzo\xc3\xab\n", 2, 1, 1, "caf\xc3\xa9\nzo\xc3\xab\n"},
        {"large-count", "a\nb\n", 2, INT_MAX, 1, "a\n"},
        // 100000 lines with the numbers 0 to 99999. Lines 2 to 99999 go.
        {"many-lines", many, 2, 99998, 99998, "0\n99999\n"},
    };
    for (const Case& c : cases) {
        write_file(path, c.text);
        auto got = remove_lines(path, c.start, c.count);
        check(got.has_value() && *got == c.want, c.name, "result");
        check(read_file(path) == c.after, c.name, "file after");
        // No temporary file stays in the directory.
        check(std::distance(fs::directory_iterator(dir), fs::directory_iterator()) == 1, c.name,
              "one file");
    }

    write_file(path, "a\nb\n");
    fs::permissions(path, fs::perms::owner_read | fs::perms::owner_write | fs::perms::group_read);
    check(remove_lines(path, 1, 1) == 1, "keeps-the-permissions", "result");
    check(fs::status(path).permissions() ==
              (fs::perms::owner_read | fs::perms::owner_write | fs::perms::group_read),
          "keeps-the-permissions", "permissions");

    auto missing = remove_lines(dir / "missing.txt", 1, 1);
    check(!missing && missing.error() == RemoveError::cannot_open, "not-found", "error");
    write_file(path, "a\nb\n");
    auto zero = remove_lines(path, 0, 1);
    check(!zero && zero.error() == RemoveError::bad_range, "start-zero", "error");
    auto negative = remove_lines(path, 1, -1);
    check(!negative && negative.error() == RemoveError::bad_range, "negative-count", "error");
    check(read_file(path) == "a\nb\n", "bad-range", "file after");

    fs::remove_all(dir);
    if (failures == 0) {
        std::cout << "ok\n";
    }
    return failures == 0 ? 0 : 1;
}
RemoveLines.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.PosixFileAttributeView;

/** Removes lines from a file and writes the rest back under the same name. */
public final class RemoveLines {
  private RemoveLines() {}

  /**
   * Removes count lines from the file at path, from line start, and returns how many it removed.
   * Line 1 is the first line. A line ends at LF, and the LF goes with the line. The result is less
   * than count if the file ends first. If no line goes, the file is not written. Otherwise the rest
   * of the file goes to a new file in the same directory, and an atomic move puts it in the place
   * of the old one.
   *
   * @throws IllegalArgumentException if start is less than 1 or count is less than 0
   * @throws java.nio.file.NoSuchFileException if the file does not exist
   */
  public static int remove(Path path, int start, int count) throws IOException {
    if (start < 1 || count < 0) {
      throw new IllegalArgumentException("bad range: start " + start + ", count " + count);
    }
    // Bytes, not lines of text: the bytes that stay do not change.
    byte[] data = Files.readAllBytes(path);
    int offset = 0;
    for (int n = 1; n < start && offset < data.length; n++) {
      offset = nextLine(data, offset);
    }
    int from = offset;
    int removed = 0;
    while (removed < count && offset < data.length) {
      offset = nextLine(data, offset);
      removed++;
    }
    if (removed == 0) {
      return 0;
    }
    Path dir = path.toAbsolutePath().getParent();
    // createTempFile makes a file with a name that no file has.
    Path tmp = Files.createTempFile(dir, "." + path.getFileName() + ".", ".tmp");
    try {
      try (FileOutputStream out = new FileOutputStream(tmp.toFile())) {
        out.write(data, 0, from);
        out.write(data, offset, data.length - offset);
        out.getFD().sync();
      }
      if (Files.getFileAttributeView(path, PosixFileAttributeView.class) != null) {
        Files.setPosixFilePermissions(tmp, Files.getPosixFilePermissions(path));
      }
      Files.move(tmp, path, StandardCopyOption.ATOMIC_MOVE);
    } catch (IOException | RuntimeException e) {
      Files.deleteIfExists(tmp);
      throw e;
    }
    return removed;
  }

  /** Returns the offset just after the line that starts at offset. */
  private static int nextLine(byte[] data, int offset) {
    while (offset < data.length && data[offset] != '\n') {
      offset++;
    }
    return offset < data.length ? offset + 1 : offset;
  }
}
RemoveLinesTest.java 94 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

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.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermissions;
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.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;

class RemoveLinesTest {
  @TempDir Path dir;

  // 100000 lines with the numbers 0 to 99999.
  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() {
    return Stream.of(
        Arguments.of("first-two", "a\nb\nc\nd\n", 1, 2, 2, "c\nd\n"),
        Arguments.of("middle", "a\nb\nc\nd\n", 2, 2, 2, "a\nd\n"),
        Arguments.of("last", "a\nb\nc\n", 3, 1, 1, "a\nb\n"),
        Arguments.of("past-the-end", "a\nb\n", 3, 1, 0, "a\nb\n"),
        Arguments.of("partly-past-the-end", "a\nb\nc\n", 2, 5, 2, "a\n"),
        Arguments.of("count-zero", "a\nb\n", 1, 0, 0, "a\nb\n"),
        Arguments.of("all-lines", "a\nb\n", 1, 2, 2, ""),
        Arguments.of("empty", "", 1, 1, 0, ""),
        Arguments.of("empty-line", "a\n\nb\n", 2, 1, 1, "a\nb\n"),
        Arguments.of("no-final-newline", "a\nb", 1, 1, 1, "b"),
        Arguments.of("remove-incomplete-line", "a\nb", 2, 1, 1, "a\n"),
        Arguments.of("crlf", "a\r\nb\r\nc\r\n", 2, 1, 1, "a\r\nc\r\n"),
        Arguments.of("lone-cr", "a\rb\nc\n", 1, 1, 1, "c\n"),
        Arguments.of("non-ascii", "caf\u00e9\nna\u00efve\nzo\u00eb\n", 2, 1, 1, "caf\u00e9\nzo\u00eb\n"),
        Arguments.of("large-count", "a\nb\n", 2, Integer.MAX_VALUE, 1, "a\n"),
        // Lines 2 to 99999 go.
        Arguments.of("many-lines", numbers(), 2, 99998, 99998, "0\n99999\n"));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void remove(String name, String text, int start, int count, int want, String after)
      throws IOException {
    Path path = dir.resolve("input.txt");
    Files.writeString(path, text, StandardCharsets.UTF_8);
    assertEquals(want, RemoveLines.remove(path, start, count), name);
    assertEquals(after, Files.readString(path, StandardCharsets.UTF_8), name);
    // No temporary file stays in the directory.
    try (Stream<Path> files = Files.list(dir)) {
      assertEquals(1, files.count(), name);
    }
  }

  @Test
  void keepsThePermissions() throws IOException {
    assumeTrue(Files.getFileAttributeView(dir, PosixFileAttributeView.class) != null);
    Path path = dir.resolve("input.txt");
    Files.writeString(path, "a\nb\n");
    Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rw-r-----"));
    assertEquals(1, RemoveLines.remove(path, 1, 1));
    assertEquals("rw-r-----", PosixFilePermissions.toString(Files.getPosixFilePermissions(path)));
  }

  @Test
  void notFound() {
    assertThrows(NoSuchFileException.class, () -> RemoveLines.remove(dir.resolve("missing.txt"), 1, 1));
  }

  @ParameterizedTest(name = "start {0}, count {1}")
  @CsvSource({"0, 1", "1, -1"})
  void badRange(int start, int count) throws IOException {
    Path path = dir.resolve("input.txt");
    Files.writeString(path, "a\nb\n");
    assertThrows(IllegalArgumentException.class, () -> RemoveLines.remove(path, start, count));
    assertArrayEquals("a\nb\n".getBytes(StandardCharsets.UTF_8), Files.readAllBytes(path));
  }
}
remove_lines.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

// mkstemp, fchmod and fsync are in POSIX, not in ISO C.
#define _POSIX_C_SOURCE 200809L

#include "remove_lines.h"

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

int remove_lines(const char *path, int start, int count) {
    if (start < 1 || count < 0) {
        errno = EINVAL;
        return -1;
    }
    FILE *src = fopen(path, "rb");
    if (src == NULL) {
        return -1;
    }
    struct stat st;
    char *tmp = NULL;
    FILE *dst = NULL;
    int fd = -1;
    if (fstat(fileno(src), &st) != 0) {
        goto fail;
    }
    // mkstemp changes the six X characters to make a name that no file has.
    // The name is path with a suffix, so it is in the same directory.
    size_t len = strlen(path);
    tmp = malloc(len + sizeof ".XXXXXX");
    if (tmp == NULL) {
        goto fail;
    }
    memcpy(tmp, path, len);
    memcpy(tmp + len, ".XXXXXX", sizeof ".XXXXXX");
    fd = mkstemp(tmp);
    if (fd < 0) {
        free(tmp);
        tmp = NULL;
        goto fail;
    }
    dst = fdopen(fd, "wb");
    if (dst == NULL) {
        close(fd);
        goto fail;
    }
    // n is the number of the line of the next byte. A long long does not
    // overflow, and n - start < count does not overflow either.
    long long n = 1;
    int removed = 0;
    int line_start = 1;
    int c;
    while ((c = getc(src)) != EOF) {
        if (n >= start && n - start < count) {
            removed += line_start;
        } else if (putc(c, dst) == EOF) {
            goto fail;
        }
        line_start = c == '\n';
        n += line_start;
    }
    if (ferror(src)) {
        goto fail;
    }
    if (removed == 0) {
        fclose(dst);
        unlink(tmp);
        free(tmp);
        fclose(src);
        return 0;
    }
    // mkstemp makes the file readable and writable only by its owner.
    if (fflush(dst) != 0 || fchmod(fd, st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO)) != 0 ||
        fsync(fd) != 0) {
        goto fail;
    }
    int closed = fclose(dst);
    dst = NULL;
    if (closed != 0 || rename(tmp, path) != 0) {
        goto fail;
    }
    free(tmp);
    fclose(src);
    return removed;

fail:;
    int e = errno;
    if (dst != NULL) {
        fclose(dst);
    }
    if (tmp != NULL) {
        unlink(tmp);
        free(tmp);
    }
    fclose(src);
    errno = e;
    return -1;
}
remove_lines.h 17 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

#ifndef REMOVE_LINES_H
#define REMOVE_LINES_H

// Removes count lines from the file at path, from line start, and returns how
// many it removed. Line 1 is the first line. A line ends at LF, and the LF
// goes with the line. The result is less than count if the file ends first.
// If no line goes, the file is not written. Otherwise the rest of the file
// goes to a new file in the same directory, and rename puts it in the place
// of the old one. On an error, the function returns -1 and sets errno:
// EINVAL if start is less than 1 or count is less than 0, ENOENT if the file
// does not exist.
int remove_lines(const char *path, int start, int count);

#endif
test_remove_lines.c 178 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

#define _POSIX_C_SOURCE 200809L

#include "remove_lines.h"

#include <dirent.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

static int failures = 0;

#define CHECK(cond, name)                                         \
    do {                                                          \
        if (!(cond)) {                                            \
            fprintf(stderr, "FAIL %s: %s\n", (name), #cond);      \
            failures++;                                           \
        }                                                         \
    } while (0)

static char dir[64];
static char path[128];

static void write_file(const char *data, size_t len) {
    FILE *f = fopen(path, "wb");
    if (f == NULL || fwrite(data, 1, len, f) != len || fclose(f) != 0) {
        perror("write_file");
        exit(1);
    }
}

// Reads the file into a buffer that the caller frees, and sets *len.
static char *read_file(size_t *len) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        perror("read_file");
        exit(1);
    }
    size_t cap = 1 << 20, n = 0;
    char *buf = malloc(cap);
    size_t got;
    while (buf != NULL && (got = fread(buf + n, 1, cap - n, f)) > 0) {
        n += got;
        if (n == cap) {
            cap *= 2;
            char *grown = realloc(buf, cap);
            if (grown == NULL) {
                free(buf);
                buf = NULL;
            } else {
                buf = grown;
            }
        }
    }
    fclose(f);
    if (buf == NULL) {
        exit(1);
    }
    *len = n;
    return buf;
}

// Counts the files in dir, without . and ..
static int files_in_dir(void) {
    DIR *d = opendir(dir);
    int n = 0;
    struct dirent *e;
    while (d != NULL && (e = readdir(d)) != NULL) {
        n += strcmp(e->d_name, ".") != 0 && strcmp(e->d_name, "..") != 0;
    }
    if (d != NULL) {
        closedir(d);
    }
    return n;
}

struct test_case {
    const char *name;
    const char *text;
    int start, count, want;
    const char *after;
};

static void check(const char *name, const char *text, size_t text_len, int start, int count,
                  int want, const char *after, size_t after_len) {
    write_file(text, text_len);
    int got = remove_lines(path, start, count);
    CHECK(got == want, name);
    size_t len;
    char *buf = read_file(&len);
    CHECK(len == after_len && memcmp(buf, after, len) == 0, name);
    free(buf);
    // No temporary file stays in the directory.
    CHECK(files_in_dir() == 1, name);
}

int main(void) {
    snprintf(dir, sizeof dir, "/tmp/remove-lines-%ld", (long)getpid());
    if (mkdir(dir, 0700) != 0) {
        perror("mkdir");
        return 1;
    }
    snprintf(path, sizeof path, "%s/input.txt", dir);
    static const struct test_case cases[] = {
        {"first-two", "a\nb\nc\nd\n", 1, 2, 2, "c\nd\n"},
        {"middle", "a\nb\nc\nd\n", 2, 2, 2, "a\nd\n"},
        {"last", "a\nb\nc\n", 3, 1, 1, "a\nb\n"},
        {"past-the-end", "a\nb\n", 3, 1, 0, "a\nb\n"},
        {"partly-past-the-end", "a\nb\nc\n", 2, 5, 2, "a\n"},
        {"count-zero", "a\nb\n", 1, 0, 0, "a\nb\n"},
        {"all-lines", "a\nb\n", 1, 2, 2, ""},
        {"empty", "", 1, 1, 0, ""},
        {"empty-line", "a\n\nb\n", 2, 1, 1, "a\nb\n"},
        {"no-final-newline", "a\nb", 1, 1, 1, "b"},
        {"remove-incomplete-line", "a\nb", 2, 1, 1, "a\n"},
        {"crlf", "a\r\nb\r\nc\r\n", 2, 1, 1, "a\r\nc\r\n"},
        {"lone-cr", "a\rb\nc\n", 1, 1, 1, "c\n"},
        {"non-ascii", "caf\xc3\xa9\nna\xc3\xafve\nzo\xc3\xab\n", 2, 1, 1, "caf\xc3\xa9\nzo\xc3\xab\n"},
        {"large-count", "a\nb\n", 2, INT_MAX, 1, "a\n"},
    };
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        check(c->name, c->text, strlen(c->text), c->start, c->count, c->want, c->after,
              strlen(c->after));
    }

    // 100000 lines with the numbers 0 to 99999. Lines 2 to 99999 go.
    size_t cap = 700000, n = 0;
    char *many = malloc(cap);
    if (many == NULL) {
        return 1;
    }
    for (int i = 0; i < 100000; i++) {
        n += (size_t)snprintf(many + n, cap - n, "%d\n", i);
    }
    check("many-lines", many, n, 2, 99998, 99998, "0\n99999\n", 8);
    free(many);

    // The file keeps its permissions.
    write_file("a\nb\n", 4);
    CHECK(chmod(path, 0640) == 0, "keeps-the-permissions");
    CHECK(remove_lines(path, 1, 1) == 1, "keeps-the-permissions");
    struct stat st;
    CHECK(stat(path, &st) == 0 && (st.st_mode & 0777) == 0640, "keeps-the-permissions");

    // If no line goes, the file is not written again.
    ino_t before = st.st_ino;
    CHECK(remove_lines(path, 5, 1) == 0, "no-change");
    CHECK(stat(path, &st) == 0 && st.st_ino == before, "no-change");

    // Errors.
    char missing[80];
    snprintf(missing, sizeof missing, "%s/missing.txt", dir);
    errno = 0;
    CHECK(remove_lines(missing, 1, 1) == -1 && errno == ENOENT, "not-found");
    write_file("a\nb\n", 4);
    errno = 0;
    CHECK(remove_lines(path, 0, 1) == -1 && errno == EINVAL, "start-zero");
    errno = 0;
    CHECK(remove_lines(path, 1, -1) == -1 && errno == EINVAL, "negative-count");
    size_t len;
    char *buf = read_file(&len);
    CHECK(len == 4 && memcmp(buf, "a\nb\n", 4) == 0, "bad-range");
    free(buf);

    unlink(path);
    rmdir(dir);
    if (failures == 0) {
        puts("ok");
    }
    return failures == 0 ? 0 : 1;
}
RemoveLines.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

/// <summary>Removes lines from a file and writes the rest back under the same name.</summary>
public static class RemoveLines
{
    /// <summary>
    /// Removes count lines from the file at path, from line start, and returns how many it
    /// removed. Line 1 is the first line. A line ends at LF, and the LF goes with the line. The
    /// result is less than count if the file ends first. If no line goes, the file is not written.
    /// Otherwise the rest of the file goes to a new file in the same directory, and File.Move puts
    /// it in the place of the old one.
    /// </summary>
    /// <exception cref="ArgumentOutOfRangeException">start is less than 1 or count is less than 0.</exception>
    /// <exception cref="FileNotFoundException">The file does not exist.</exception>
    public static int Remove(string path, int start, int count)
    {
        ArgumentOutOfRangeException.ThrowIfLessThan(start, 1);
        ArgumentOutOfRangeException.ThrowIfNegative(count);
        // Bytes, not lines of text: the bytes that stay do not change.
        byte[] data = File.ReadAllBytes(path);
        int offset = 0;
        for (int n = 1; n < start && offset < data.Length; n++)
        {
            offset = NextLine(data, offset);
        }
        int from = offset;
        int removed = 0;
        while (removed < count && offset < data.Length)
        {
            offset = NextLine(data, offset);
            removed++;
        }
        if (removed == 0)
        {
            return 0;
        }
        string dir = Path.GetDirectoryName(Path.GetFullPath(path))!;
        string tmp = Path.Combine(dir, $".{Path.GetFileName(path)}.{Guid.NewGuid():N}.tmp");
        try
        {
            // CreateNew fails if a file with the name exists.
            using (var stream = new FileStream(tmp, FileMode.CreateNew, FileAccess.Write))
            {
                stream.Write(data, 0, from);
                stream.Write(data, offset, data.Length - offset);
                // Flush(true) also writes the data from the operating system to the disk.
                stream.Flush(true);
            }
            if (!OperatingSystem.IsWindows())
            {
                File.SetUnixFileMode(tmp, File.GetUnixFileMode(path));
            }
            File.Move(tmp, path, overwrite: true);
        }
        catch
        {
            File.Delete(tmp);
            throw;
        }
        return removed;
    }

    // Returns the offset just after the line that starts at offset.
    private static int NextLine(byte[] data, int offset)
    {
        int lf = Array.IndexOf(data, (byte)'\n', offset);
        return lf == -1 ? data.Length : lf + 1;
    }
}
RemoveLinesTests.cs 83 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

using System.Text;
using Xunit;

public sealed class RemoveLinesTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("remove-lines-").FullName;

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

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

    public static TheoryData<string, string, int, int, int, string> Cases => new()
    {
        { "first-two", "a\nb\nc\nd\n", 1, 2, 2, "c\nd\n" },
        { "middle", "a\nb\nc\nd\n", 2, 2, 2, "a\nd\n" },
        { "last", "a\nb\nc\n", 3, 1, 1, "a\nb\n" },
        { "past-the-end", "a\nb\n", 3, 1, 0, "a\nb\n" },
        { "partly-past-the-end", "a\nb\nc\n", 2, 5, 2, "a\n" },
        { "count-zero", "a\nb\n", 1, 0, 0, "a\nb\n" },
        { "all-lines", "a\nb\n", 1, 2, 2, "" },
        { "empty", "", 1, 1, 0, "" },
        { "empty-line", "a\n\nb\n", 2, 1, 1, "a\nb\n" },
        { "no-final-newline", "a\nb", 1, 1, 1, "b" },
        { "remove-incomplete-line", "a\nb", 2, 1, 1, "a\n" },
        { "crlf", "a\r\nb\r\nc\r\n", 2, 1, 1, "a\r\nc\r\n" },
        { "lone-cr", "a\rb\nc\n", 1, 1, 1, "c\n" },
        { "non-ascii", "caf\u00e9\nna\u00efve\nzo\u00eb\n", 2, 1, 1, "caf\u00e9\nzo\u00eb\n" },
        { "large-count", "a\nb\n", 2, int.MaxValue, 1, "a\n" },
        // Lines 2 to 99999 go.
        { "many-lines", Numbers(), 2, 99998, 99998, "0\n99999\n" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Remove(string name, string text, int start, int count, int want, string after)
    {
        string path = Path.Combine(dir, "input.txt");
        // UTF8Encoding(false) writes no byte order mark.
        File.WriteAllText(path, text, new UTF8Encoding(false));
        Assert.Equal(want, RemoveLines.Remove(path, start, count));
        Assert.Equal(after, File.ReadAllText(path, Encoding.UTF8));
        // No temporary file stays in the directory.
        Assert.Single(Directory.GetFiles(dir));
        _ = name;
    }

    [Fact]
    public void KeepsThePermissions()
    {
        if (OperatingSystem.IsWindows())
        {
            return;
        }
        string path = Path.Combine(dir, "input.txt");
        File.WriteAllText(path, "a\nb\n");
        var mode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead;
        File.SetUnixFileMode(path, mode);
        Assert.Equal(1, RemoveLines.Remove(path, 1, 1));
        Assert.Equal(mode, File.GetUnixFileMode(path));
    }

    [Fact]
    public void NotFound()
    {
        Assert.Throws<FileNotFoundException>(() => RemoveLines.Remove(Path.Combine(dir, "missing.txt"), 1, 1));
    }

    [Theory]
    [InlineData(0, 1)]
    [InlineData(1, -1)]
    public void BadRange(int start, int count)
    {
        string path = Path.Combine(dir, "input.txt");
        File.WriteAllText(path, "a\nb\n");
        Assert.Throws<ArgumentOutOfRangeException>(() => RemoveLines.Remove(path, start, count));
        Assert.Equal("a\nb\n", File.ReadAllText(path));
    }
}
removeLines.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

import { randomUUID } from "node:crypto";
import { chmodSync, closeSync, fsyncSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { basename, dirname, join } from "node:path";

// Returns the offset just after the line that starts at offset: after the
// next LF, or at the end of the data if there is no LF.
function nextLine(data, offset) {
  const lf = data.indexOf(10, offset);
  return lf === -1 ? data.length : lf + 1;
}

// Removes count lines from the file at path, from line start, and returns how
// many it removed. Line 1 is the first line. A line ends at LF, and the LF
// goes with the line. The result is less than count if the file ends first.
// If no line goes, the file is not written. Otherwise the rest of the file
// goes to a new file in the same directory, and renameSync puts it in the
// place of the old one. Throws a RangeError if start is less than 1 or count
// is less than 0, and an error whose code is "ENOENT" if the file does not
// exist.
export function removeLines(path, start, count) {
  if (!Number.isInteger(start) || !Number.isInteger(count) || start < 1 || count < 0) {
    throw new RangeError(`bad range: start ${start}, count ${count}`);
  }
  // A Buffer, not a string: the bytes do not change.
  const data = readFileSync(path);
  let offset = 0;
  for (let number = 1; number < start && offset < data.length; number++) {
    offset = nextLine(data, offset);
  }
  const from = offset;
  let removed = 0;
  while (removed < count && offset < data.length) {
    offset = nextLine(data, offset);
    removed++;
  }
  if (removed === 0) return 0;
  const tmp = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
  try {
    // "wx" fails if the file exists, so the code does not write over a file
    // with the same name.
    const fd = openSync(tmp, "wx", 0o600);
    try {
      writeFileSync(fd, Buffer.concat([data.subarray(0, from), data.subarray(offset)]));
      fsyncSync(fd);
    } finally {
      closeSync(fd);
    }
    chmodSync(tmp, statSync(path).mode & 0o7777);
    renameSync(tmp, path);
  } catch (err) {
    rmSync(tmp, { force: true });
    throw err;
  }
  return removed;
}
removeLines.test.js 68 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

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

const root = mkdtempSync(join(tmpdir(), "remove-lines-"));
after(() => rmSync(root, { recursive: true }));

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

// [name, the text of the file, start, count, the result, the text after]
const cases = [
  ["first-two", "a\nb\nc\nd\n", 1, 2, 2, "c\nd\n"],
  ["middle", "a\nb\nc\nd\n", 2, 2, 2, "a\nd\n"],
  ["last", "a\nb\nc\n", 3, 1, 1, "a\nb\n"],
  ["past-the-end", "a\nb\n", 3, 1, 0, "a\nb\n"],
  ["partly-past-the-end", "a\nb\nc\n", 2, 5, 2, "a\n"],
  ["count-zero", "a\nb\n", 1, 0, 0, "a\nb\n"],
  ["all-lines", "a\nb\n", 1, 2, 2, ""],
  ["empty", "", 1, 1, 0, ""],
  ["empty-line", "a\n\nb\n", 2, 1, 1, "a\nb\n"],
  ["no-final-newline", "a\nb", 1, 1, 1, "b"],
  ["remove-incomplete-line", "a\nb", 2, 1, 1, "a\n"],
  ["crlf", "a\r\nb\r\nc\r\n", 2, 1, 1, "a\r\nc\r\n"],
  ["lone-cr", "a\rb\nc\n", 1, 1, 1, "c\n"],
  ["non-ascii", "caf\u00e9\nna\u00efve\nzo\u00eb\n", 2, 1, 1, "caf\u00e9\nzo\u00eb\n"],
  ["large-count", "a\nb\n", 2, 2147483647, 1, "a\n"],
  // 100000 lines with the numbers 0 to 99999. Lines 2 to 99999 go.
  ["many-lines", numbers, 2, 99998, 99998, "0\n99999\n"],
];

for (const [name, text, start, count, want, afterText] of cases) {
  test(name, () => {
    const dir = mkdtempSync(join(root, "case-"));
    const path = join(dir, "input.txt");
    writeFileSync(path, text, "utf8");
    assert.equal(removeLines(path, start, count), want);
    assert.equal(readFileSync(path, "utf8"), afterText);
    // No temporary file stays in the directory.
    assert.deepEqual(readdirSync(dir), ["input.txt"]);
  });
}

test("keeps-the-permissions", { skip: process.platform === "win32" }, () => {
  const path = join(mkdtempSync(join(root, "case-")), "input.txt");
  writeFileSync(path, "a\nb\n");
  chmodSync(path, 0o640);
  assert.equal(removeLines(path, 1, 1), 1);
  assert.equal(statSync(path).mode & 0o777, 0o640);
});

test("not-found", () => {
  assert.throws(() => removeLines(join(root, "missing.txt"), 1, 1), { code: "ENOENT" });
});

for (const [name, start, count] of [["start-zero", 0, 1], ["negative-count", 1, -1]]) {
  test(name, () => {
    const path = join(mkdtempSync(join(root, "case-")), "input.txt");
    writeFileSync(path, "a\nb\n");
    assert.throws(() => removeLines(path, start, count), RangeError);
    assert.equal(readFileSync(path, "utf8"), "a\nb\n");
  });
}
removeLines.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

import { randomUUID } from "node:crypto";
import { chmodSync, closeSync, fsyncSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { basename, dirname, join } from "node:path";

// Returns the offset just after the line that starts at offset: after the
// next LF, or at the end of the data if there is no LF.
function nextLine(data: Buffer, offset: number): number {
  const lf = data.indexOf(10, offset);
  return lf === -1 ? data.length : lf + 1;
}

// Removes count lines from the file at path, from line start, and returns how
// many it removed. Line 1 is the first line. A line ends at LF, and the LF
// goes with the line. The result is less than count if the file ends first.
// If no line goes, the file is not written. Otherwise the rest of the file
// goes to a new file in the same directory, and renameSync puts it in the
// place of the old one. Throws a RangeError if start is less than 1 or count
// is less than 0, and an error whose code is "ENOENT" if the file does not
// exist.
export function removeLines(path: string, start: number, count: number): number {
  if (!Number.isInteger(start) || !Number.isInteger(count) || start < 1 || count < 0) {
    throw new RangeError(`bad range: start ${start}, count ${count}`);
  }
  // A Buffer, not a string: the bytes do not change.
  const data = readFileSync(path);
  let offset = 0;
  for (let number = 1; number < start && offset < data.length; number++) {
    offset = nextLine(data, offset);
  }
  const from = offset;
  let removed = 0;
  while (removed < count && offset < data.length) {
    offset = nextLine(data, offset);
    removed++;
  }
  if (removed === 0) return 0;
  const tmp = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
  try {
    // "wx" fails if the file exists, so the code does not write over a file
    // with the same name.
    const fd = openSync(tmp, "wx", 0o600);
    try {
      writeFileSync(fd, Buffer.concat([data.subarray(0, from), data.subarray(offset)]));
      fsyncSync(fd);
    } finally {
      closeSync(fd);
    }
    chmodSync(tmp, statSync(path).mode & 0o7777);
    renameSync(tmp, path);
  } catch (err) {
    rmSync(tmp, { force: true });
    throw err;
  }
  return removed;
}
removeLines.test.ts 68 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

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

const root = mkdtempSync(join(tmpdir(), "remove-lines-"));
after(() => rmSync(root, { recursive: true }));

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

// [name, the text of the file, start, count, the result, the text after]
const cases: [string, string, number, number, number, string][] = [
  ["first-two", "a\nb\nc\nd\n", 1, 2, 2, "c\nd\n"],
  ["middle", "a\nb\nc\nd\n", 2, 2, 2, "a\nd\n"],
  ["last", "a\nb\nc\n", 3, 1, 1, "a\nb\n"],
  ["past-the-end", "a\nb\n", 3, 1, 0, "a\nb\n"],
  ["partly-past-the-end", "a\nb\nc\n", 2, 5, 2, "a\n"],
  ["count-zero", "a\nb\n", 1, 0, 0, "a\nb\n"],
  ["all-lines", "a\nb\n", 1, 2, 2, ""],
  ["empty", "", 1, 1, 0, ""],
  ["empty-line", "a\n\nb\n", 2, 1, 1, "a\nb\n"],
  ["no-final-newline", "a\nb", 1, 1, 1, "b"],
  ["remove-incomplete-line", "a\nb", 2, 1, 1, "a\n"],
  ["crlf", "a\r\nb\r\nc\r\n", 2, 1, 1, "a\r\nc\r\n"],
  ["lone-cr", "a\rb\nc\n", 1, 1, 1, "c\n"],
  ["non-ascii", "caf\u00e9\nna\u00efve\nzo\u00eb\n", 2, 1, 1, "caf\u00e9\nzo\u00eb\n"],
  ["large-count", "a\nb\n", 2, 2147483647, 1, "a\n"],
  // 100000 lines with the numbers 0 to 99999. Lines 2 to 99999 go.
  ["many-lines", numbers, 2, 99998, 99998, "0\n99999\n"],
];

for (const [name, text, start, count, want, afterText] of cases) {
  test(name, () => {
    const dir = mkdtempSync(join(root, "case-"));
    const path = join(dir, "input.txt");
    writeFileSync(path, text, "utf8");
    assert.equal(removeLines(path, start, count), want);
    assert.equal(readFileSync(path, "utf8"), afterText);
    // No temporary file stays in the directory.
    assert.deepEqual(readdirSync(dir), ["input.txt"]);
  });
}

test("keeps-the-permissions", { skip: process.platform === "win32" }, () => {
  const path = join(mkdtempSync(join(root, "case-")), "input.txt");
  writeFileSync(path, "a\nb\n");
  chmodSync(path, 0o640);
  assert.equal(removeLines(path, 1, 1), 1);
  assert.equal(statSync(path).mode & 0o777, 0o640);
});

test("not-found", () => {
  assert.throws(() => removeLines(join(root, "missing.txt"), 1, 1), { code: "ENOENT" });
});

for (const [name, start, count] of [["start-zero", 0, 1], ["negative-count", 1, -1]] as const) {
  test(name, () => {
    const path = join(mkdtempSync(join(root, "case-")), "input.txt");
    writeFileSync(path, "a\nb\n");
    assert.throws(() => removeLines(path, start, count), RangeError);
    assert.equal(readFileSync(path, "utf8"), "a\nb\n");
  });
}
remove_lines.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

// Package removelines removes lines from a file and writes the rest back under
// the same name.
package removelines

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
)

// ErrBadRange is the error when start is less than 1 or count is less than 0.
var ErrBadRange = errors.New("removelines: start must be 1 or more and count 0 or more")

// RemoveLines removes count lines from the file at path, from line start, and
// returns how many it removed. Line 1 is the first line. A line ends at LF,
// and the LF goes with the line. The result is less than count if the file
// ends first. If no line goes, the file is not written. Otherwise the rest of
// the file goes to a new file in the same directory, and os.Rename puts it in
// the place of the old one. A missing file gives an error for which
// errors.Is(err, fs.ErrNotExist) is true.
func RemoveLines(path string, start, count int) (removed int, err error) {
	if start < 1 || count < 0 {
		return 0, fmt.Errorf("%w: start %d, count %d", ErrBadRange, start, count)
	}
	src, err := os.Open(path)
	if err != nil {
		return 0, err
	}
	defer src.Close()
	info, err := src.Stat()
	if err != nil {
		return 0, err
	}
	tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*.tmp")
	if err != nil {
		return 0, err
	}
	// On each return before the rename, close and remove the new file.
	renamed := false
	defer func() {
		if !renamed {
			tmp.Close()
			os.Remove(tmp.Name())
		}
	}()
	r := bufio.NewReader(src)
	w := bufio.NewWriter(tmp)
	for n := 1; ; n++ {
		// ReadBytes reads up to and with the next LF, so a CR stays in the
		// line. At the end of the file, it returns the last line with no LF
		// and io.EOF.
		line, err := r.ReadBytes('\n')
		if len(line) > 0 {
			if n >= start && n-start < count {
				removed++
			} else if _, werr := w.Write(line); werr != nil {
				return 0, werr
			}
		}
		if errors.Is(err, io.EOF) {
			break
		}
		if err != nil {
			return 0, err
		}
	}
	if removed == 0 {
		return 0, nil
	}
	if err := w.Flush(); err != nil {
		return 0, err
	}
	// CreateTemp makes the file with mode 0600.
	if err := tmp.Chmod(info.Mode().Perm()); err != nil {
		return 0, err
	}
	if err := tmp.Sync(); err != nil {
		return 0, err
	}
	if err := tmp.Close(); err != nil {
		return 0, err
	}
	if err := os.Rename(tmp.Name(), path); err != nil {
		return 0, err
	}
	renamed = true
	return removed, nil
}
remove_lines_test.go 131 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

package removelines

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

func numbers() string {
	var b strings.Builder
	for i := range 100000 {
		b.WriteString(strconv.Itoa(i) + "\n")
	}
	return b.String()
}

func TestRemoveLines(t *testing.T) {
	many := numbers()
	cases := []struct {
		name         string
		text         string
		start, count int
		want         int
		after        string
	}{
		{"first-two", "a\nb\nc\nd\n", 1, 2, 2, "c\nd\n"},
		{"middle", "a\nb\nc\nd\n", 2, 2, 2, "a\nd\n"},
		{"last", "a\nb\nc\n", 3, 1, 1, "a\nb\n"},
		{"past-the-end", "a\nb\n", 3, 1, 0, "a\nb\n"},
		{"partly-past-the-end", "a\nb\nc\n", 2, 5, 2, "a\n"},
		{"count-zero", "a\nb\n", 1, 0, 0, "a\nb\n"},
		{"all-lines", "a\nb\n", 1, 2, 2, ""},
		{"empty", "", 1, 1, 0, ""},
		{"empty-line", "a\n\nb\n", 2, 1, 1, "a\nb\n"},
		{"no-final-newline", "a\nb", 1, 1, 1, "b"},
		{"remove-incomplete-line", "a\nb", 2, 1, 1, "a\n"},
		{"crlf", "a\r\nb\r\nc\r\n", 2, 1, 1, "a\r\nc\r\n"},
		{"lone-cr", "a\rb\nc\n", 1, 1, 1, "c\n"},
		{"non-ascii", "caf\u00e9\nna\u00efve\nzo\u00eb\n", 2, 1, 1, "caf\u00e9\nzo\u00eb\n"},
		{"large-count", "a\nb\n", 2, 2147483647, 1, "a\n"},
		// 100000 lines with the numbers 0 to 99999. Lines 2 to 99999 go.
		{"many-lines", many, 2, 99998, 99998, "0\n99999\n"},
		// A line longer than the 4096-byte buffer of bufio.Reader.
		{"long-line", "a\n" + strings.Repeat("x", 10000) + "\nb\n", 2, 1, 1, "a\nb\n"},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			dir := t.TempDir()
			path := filepath.Join(dir, "input.txt")
			if err := os.WriteFile(path, []byte(c.text), 0o644); err != nil {
				t.Fatal(err)
			}
			got, err := RemoveLines(path, c.start, c.count)
			if err != nil || got != c.want {
				t.Fatalf("RemoveLines(%d, %d) = %d, %v; want %d", c.start, c.count, got, err, c.want)
			}
			b, err := os.ReadFile(path)
			if err != nil || string(b) != c.after {
				t.Fatalf("file after = %q, %v; want %q", b, err, c.after)
			}
			// No temporary file stays in the directory.
			if entries, _ := os.ReadDir(dir); len(entries) != 1 {
				t.Fatalf("%d files in the directory, want 1", len(entries))
			}
		})
	}
}

func TestNoChangeKeepsTheFile(t *testing.T) {
	path := filepath.Join(t.TempDir(), "input.txt")
	if err := os.WriteFile(path, []byte("a\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	before, _ := os.Stat(path)
	if got, err := RemoveLines(path, 2, 1); err != nil || got != 0 {
		t.Fatalf("RemoveLines = %d, %v; want 0", got, err)
	}
	after, _ := os.Stat(path)
	if !os.SameFile(before, after) {
		t.Fatal("the file was written again")
	}
}

func TestKeepsThePermissions(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("POSIX permission bits")
	}
	path := filepath.Join(t.TempDir(), "input.txt")
	if err := os.WriteFile(path, []byte("a\nb\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	if err := os.Chmod(path, 0o640); err != nil {
		t.Fatal(err)
	}
	if _, err := RemoveLines(path, 1, 1); err != nil {
		t.Fatal(err)
	}
	if info, _ := os.Stat(path); info.Mode().Perm() != 0o640 {
		t.Fatalf("mode %v, want 0640", info.Mode().Perm())
	}
}

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

func TestBadRange(t *testing.T) {
	for _, r := range [][2]int{{0, 1}, {1, -1}} {
		path := filepath.Join(t.TempDir(), "input.txt")
		if err := os.WriteFile(path, []byte("a\nb\n"), 0o644); err != nil {
			t.Fatal(err)
		}
		if _, err := RemoveLines(path, r[0], r[1]); !errors.Is(err, ErrBadRange) {
			t.Fatalf("RemoveLines(%d, %d) err = %v, want ErrBadRange", r[0], r[1], err)
		}
		if b, _ := os.ReadFile(path); string(b) != "a\nb\n" {
			t.Fatalf("file after = %q", b)
		}
	}
}
remove_lines.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

//! Removes lines from a file and writes the rest back under the same name.

use std::fs::{self, File, OpenOptions};
use std::io::{self, BufRead, BufReader, BufWriter, ErrorKind, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

/// Removes `count` lines from the file at `path`, from line `start`, and
/// returns how many it removed.
///
/// Line 1 is the first line. A line ends at LF, and the LF goes with the line.
/// The result is less than `count` if the file ends first. If no line goes,
/// the file is not written. Otherwise the rest of the file goes to a new file
/// in the same directory, and `fs::rename` puts it in the place of the old
/// one. A `start` less than 1 or a `count` less than 0 gives an error of kind
/// `InvalidInput`, and a missing file gives an error of kind `NotFound`.
pub fn remove_lines(path: impl AsRef<Path>, start: i32, count: i32) -> io::Result<i32> {
    let path = path.as_ref();
    if start < 1 || count < 0 {
        return Err(io::Error::new(
            ErrorKind::InvalidInput,
            format!("bad range: start {start}, count {count}"),
        ));
    }
    let src = File::open(path)?;
    let permissions = src.metadata()?.permissions();
    let (tmp_path, tmp) = create_temp(path)?;
    let result = copy_and_replace(src, tmp, &tmp_path, path, permissions, start, count);
    if !matches!(result, Ok(n) if n > 0) {
        // The rename did not happen, so the new file is still there.
        let _ = fs::remove_file(&tmp_path);
    }
    result
}

fn copy_and_replace(
    src: File,
    tmp: File,
    tmp_path: &Path,
    path: &Path,
    permissions: fs::Permissions,
    start: i32,
    count: i32,
) -> io::Result<i32> {
    // remove_lines checked that start and count are not negative. u64 line
    // numbers do not overflow.
    let (start, count) = (
        u64::from(start.unsigned_abs()),
        u64::from(count.unsigned_abs()),
    );
    let mut reader = BufReader::new(src);
    let mut writer = BufWriter::new(tmp);
    let mut line = Vec::new();
    let mut removed = 0;
    for n in 1u64.. {
        line.clear();
        // read_until reads up to and with the next LF, so a CR stays in the
        // line. It returns 0 at the end of the file.
        if reader.read_until(b'\n', &mut line)? == 0 {
            break;
        }
        if n >= start && n - start < count {
            removed += 1;
        } else {
            writer.write_all(&line)?;
        }
    }
    if removed == 0 {
        return Ok(0);
    }
    let tmp = writer.into_inner().map_err(|e| e.into_error())?;
    // The new file has the default permissions, so it gets the old ones.
    tmp.set_permissions(permissions)?;
    tmp.sync_all()?;
    drop(tmp);
    fs::rename(tmp_path, path)?;
    Ok(removed)
}

/// Creates a new file next to `path` with a name that no file has.
fn create_temp(path: &Path) -> io::Result<(PathBuf, File)> {
    static NEXT: AtomicU64 = AtomicU64::new(0);
    let dir = path.parent().unwrap_or(Path::new(""));
    let name = path.file_name().unwrap_or_default().to_string_lossy();
    loop {
        let n = NEXT.fetch_add(1, Ordering::Relaxed);
        let tmp_path = dir.join(format!(".{name}.{}.{n}.tmp", std::process::id()));
        // create_new fails if the file exists, so the code does not write
        // over a file with the same name.
        match OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&tmp_path)
        {
            Ok(file) => return Ok((tmp_path, file)),
            Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
            Err(e) => return Err(e),
        }
    }
}
tests/remove_lines_test.rs 105 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/remove-lines-from-a-file/.

use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU32, Ordering};

use algo_remove_lines::remove_lines;

/// (name, the bytes of the file, start, count, the result, the bytes after)
type Case<'a> = (&'a str, &'a [u8], i32, i32, i32, &'a [u8]);

/// Makes a new directory for one test and writes the file input.txt in it.
fn temp_file(text: &[u8]) -> (PathBuf, PathBuf) {
    static NEXT: AtomicU32 = AtomicU32::new(0);
    let n = NEXT.fetch_add(1, Ordering::Relaxed);
    let dir = std::env::temp_dir().join(format!("remove-lines-{}-{n}", std::process::id()));
    fs::create_dir_all(&dir).unwrap();
    let path = dir.join("input.txt");
    fs::write(&path, text).unwrap();
    (dir, path)
}

#[test]
fn cases() {
    // 100000 lines with the numbers 0 to 99999. Lines 2 to 99999 go.
    let many: String = (0..100000).map(|i| format!("{i}\n")).collect();
    let cases: [Case; 16] = [
        ("first-two", b"a\nb\nc\nd\n", 1, 2, 2, b"c\nd\n"),
        ("middle", b"a\nb\nc\nd\n", 2, 2, 2, b"a\nd\n"),
        ("last", b"a\nb\nc\n", 3, 1, 1, b"a\nb\n"),
        ("past-the-end", b"a\nb\n", 3, 1, 0, b"a\nb\n"),
        ("partly-past-the-end", b"a\nb\nc\n", 2, 5, 2, b"a\n"),
        ("count-zero", b"a\nb\n", 1, 0, 0, b"a\nb\n"),
        ("all-lines", b"a\nb\n", 1, 2, 2, b""),
        ("empty", b"", 1, 1, 0, b""),
        ("empty-line", b"a\n\nb\n", 2, 1, 1, b"a\nb\n"),
        ("no-final-newline", b"a\nb", 1, 1, 1, b"b"),
        ("remove-incomplete-line", b"a\nb", 2, 1, 1, b"a\n"),
        ("crlf", b"a\r\nb\r\nc\r\n", 2, 1, 1, b"a\r\nc\r\n"),
        ("lone-cr", b"a\rb\nc\n", 1, 1, 1, b"c\n"),
        (
            "non-ascii",
            "caf\u{e9}\nna\u{ef}ve\nzo\u{eb}\n".as_bytes(),
            2,
            1,
            1,
            "caf\u{e9}\nzo\u{eb}\n".as_bytes(),
        ),
        ("large-count", b"a\nb\n", 2, i32::MAX, 1, b"a\n"),
        (
            "many-lines",
            many.as_bytes(),
            2,
            99998,
            99998,
            b"0\n99999\n",
        ),
    ];
    for (name, text, start, count, want, after) in cases {
        let (dir, path) = temp_file(text);
        assert_eq!(remove_lines(&path, start, count).unwrap(), want, "{name}");
        assert_eq!(fs::read(&path).unwrap(), after, "{name}");
        // No temporary file stays in the directory.
        assert_eq!(fs::read_dir(&dir).unwrap().count(), 1, "{name}");
        fs::remove_dir_all(&dir).unwrap();
    }
}

#[cfg(unix)]
#[test]
fn keeps_the_permissions() {
    use std::os::unix::fs::PermissionsExt;
    let (dir, path) = temp_file(b"a\nb\n");
    fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).unwrap();
    assert_eq!(remove_lines(&path, 1, 1).unwrap(), 1);
    assert_eq!(
        fs::metadata(&path).unwrap().permissions().mode() & 0o777,
        0o640
    );
    fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn not_found() {
    let path = std::env::temp_dir().join("remove-lines-missing.txt");
    assert_eq!(
        remove_lines(&path, 1, 1).unwrap_err().kind(),
        ErrorKind::NotFound
    );
}

#[test]
fn bad_range() {
    for (start, count) in [(0, 1), (1, -1)] {
        let (dir, path) = temp_file(b"a\nb\n");
        assert_eq!(
            remove_lines(&path, start, count).unwrap_err().kind(),
            ErrorKind::InvalidInput
        );
        assert_eq!(fs::read(&path).unwrap(), b"a\nb\n");
        fs::remove_dir_all(&dir).unwrap();
    }
}
remove_lines.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/remove-lines-from-a-file/.

# remove_lines PATH START COUNT
# Removes COUNT lines from the file at PATH, from line START, and prints how
# many it removed. Line 1 is the first line. A line ends at LF, and the LF goes
# with the line. If no line goes, the file is not written. Otherwise the rest
# of the file goes to a new file in the same directory, and mv puts it in the
# place of the old one. Returns 2 with a message if START is not 1 or more, if
# COUNT is not 0 or more, or if the file cannot be read or written.
remove_lines() {
  local file=$1 start=$2 count=$3 total removed tmp
  if ! [[ $start =~ ^[0-9]+$ && $count =~ ^[0-9]+$ ]] || ((10#$start < 1)); then
    printf 'remove_lines: bad range: start %s, count %s\n' "$start" "$count" >&2
    return 2
  fi
  # 10# reads 08 as eight, not as a bad octal number.
  start=$((10#$start)) count=$((10#$count))
  [[ -f $file && -r $file ]] || { printf 'remove_lines: cannot read %s\n' "$file" >&2; return 2; }
  # NR in the END action is the number of lines, with a last line with no LF.
  total=$(awk 'END { print NR }' <"$file") || return 2
  removed=$((total - start + 1))
  ((removed < 0)) && removed=0
  ((removed > count)) && removed=$count
  if ((removed == 0)); then
    echo 0
    return 0
  fi
  tmp=$(mktemp "$file.XXXXXX") || return 2
  # cp -p gives the new file the permissions of the old one, and > keeps them.
  # head and tail copy the bytes as they are, also a last line with no LF.
  if cp -p -- "$file" "$tmp" &&
    {
      # head -n 0 is not portable, so the code does not run it.
      if ((start > 1)); then head -n "$((start - 1))" -- "$file"; fi &&
        tail -n "+$((start + removed))" -- "$file"
    } >"$tmp" &&
    mv -f -- "$tmp" "$file"; then
    echo "$removed"
  else
    rm -f -- "$tmp"
    return 2
  fi
}
test_remove_lines.bats 65 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/remove-lines-from-a-file/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/remove_lines.sh"
  dir="$BATS_TEST_TMPDIR/case"
  mkdir -p "$dir"
  file="$dir/input.txt"
}

check() { # check BYTES START COUNT WANT AFTER
  printf '%b' "$1" >"$file"
  [ "$(remove_lines "$file" "$2" "$3")" = "$4" ]
  # The x keeps a final LF, which $(...) removes.
  [ "$(cat "$file"; printf x)" = "$(printf '%bx' "$5")" ]
  # No temporary file stays in the directory.
  [ "$(ls -A "$dir")" = "input.txt" ]
}

@test "first-two" { check 'a\nb\nc\nd\n' 1 2 2 'c\nd\n'; }
@test "middle" { check 'a\nb\nc\nd\n' 2 2 2 'a\nd\n'; }
@test "last" { check 'a\nb\nc\n' 3 1 1 'a\nb\n'; }
@test "past-the-end" { check 'a\nb\n' 3 1 0 'a\nb\n'; }
@test "partly-past-the-end" { check 'a\nb\nc\n' 2 5 2 'a\n'; }
@test "count-zero" { check 'a\nb\n' 1 0 0 'a\nb\n'; }
@test "all-lines" { check 'a\nb\n' 1 2 2 ''; }
@test "empty" { check '' 1 1 0 ''; }
@test "empty-line" { check 'a\n\nb\n' 2 1 1 'a\nb\n'; }
@test "no-final-newline" { check 'a\nb' 1 1 1 'b'; }
@test "remove-incomplete-line" { check 'a\nb' 2 1 1 'a\n'; }
@test "crlf" { check 'a\r\nb\r\nc\r\n' 2 1 1 'a\r\nc\r\n'; }
@test "lone-cr" { check 'a\rb\nc\n' 1 1 1 'c\n'; }
@test "non-ascii" { check 'caf\xc3\xa9\nna\xc3\xafve\nzo\xc3\xab\n' 2 1 1 'caf\xc3\xa9\nzo\xc3\xab\n'; }
@test "large-count" { check 'a\nb\n' 2 2147483647 1 'a\n'; }

@test "many-lines" {
  seq 0 99999 >"$file"
  [ "$(remove_lines "$file" 2 99998)" = 99998 ]
  [ "$(cat "$file")" = "$(printf '0\n99999')" ]
}

@test "keeps-the-permissions" {
  printf 'a\nb\n' >"$file"
  chmod 640 "$file"
  [ "$(remove_lines "$file" 1 1)" = 1 ]
  [ "$(ls -l "$file" | cut -c 1-10)" = "-rw-r-----" ]
}

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

@test "bad-range" {
  printf 'a\nb\n' >"$file"
  run remove_lines "$file" 0 1
  [ "$status" -eq 2 ]
  run remove_lines "$file" 1 -1
  [ "$status" -eq 2 ]
  [ "$(cat "$file")" = "$(printf 'a\nb')" ]
}

References

  1. Rosetta Code, Remove lines from a file (task text, from acmeism/RosettaCodeData), task text
  2. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), rename, renameat, DESCRIPTION; ERRORS (EXDEV)
  3. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), fsync, DESCRIPTION
  4. The Python Standard Library, shutil, copymode
  5. The Python Standard Library, os, os.replace
  6. Node.js documentation, File system, File system flags; fs.renameSync
  7. Java SE 25 API, java.nio.file.Files, createTempFile; move (ATOMIC_MOVE)
  8. .NET API reference, File.SetUnixFileMode, SetUnixFileMode(String, UnixFileMode)
  9. .NET API reference, File.Move, Move(String, String, Boolean)
  10. Go standard library, package os, CreateTemp; File.Sync; Rename
  11. The Rust Standard Library, std::fs::OpenOptions, create_new
  12. The Rust Standard Library, std::fs::rename, Description
  13. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), mkdtemp, mkostemp, mkstemp, DESCRIPTION
  14. cppreference.com, std::ios_base::openmode, noreplace
  15. cppreference.com, std::filesystem::rename, Description
  16. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), tail, OPTIONS (-n)
  17. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), Shell Command Language, 2.7.2 Redirecting Output; 2.9.1 Simple Commands
  18. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), sed, SYNOPSIS
  19. FreeBSD manual page, sed(1), SYNOPSIS; DESCRIPTION (-I, -i)
  20. The Python Standard Library, tempfile, mkstemp
  21. MDN Web Docs, String.prototype.split(), Description
  22. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), head, OPTIONS (-c, -n)

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