Taskintro
Count the lines of a file
Also called line count, count newlines in a file, wc -l, number of lines in a text file.
Count the LF bytes of a file as wc -l does, and the lines with a last line that has no LF, by reading the bytes in chunks without decoding them.
- Evidence
- Code in 10 languages
Task
Count the lines of a file. Each solution returns two numbers:
- newlines: the number of LF bytes (
\n, 0x0A) in the file. This is the number thatwc -lprints. POSIX says thatwc -lshall "Write to the standard output the number of characters in each input file."1 - lines: the number of lines, which also counts a last line that has no LF. It is newlines plus 1 if the file is not empty and its last byte is not LF.
The two numbers are different only when the file does not end with LF. POSIX defines a line as "A sequence of zero or more non- characters plus a terminating character."2 It defines an incomplete line as "A sequence of one or more non- characters at the end of the file."2 So newlines counts the lines, and lines counts the lines and the incomplete line. Use newlines when the result must agree with wc -l. Use lines when an incomplete line must also count, for example when you number the lines of a file.
The file can hold any bytes. The solution does not decode the file, so bytes that are not valid UTF-8 and NUL bytes are not errors. Only LF ends a line. CR alone, VT, FF, NEL (U+0085) and U+2028 do not. In a CRLF file, each CRLF holds one LF, so the count is correct. An empty file gives (0, 0). If the file does not exist, the solution reports an error.
The file can be larger than the memory. So the solution reads it in chunks of 64 KiB, counts the LF bytes in each chunk, and keeps the last byte that it read.
Solutions
Each solution has the same loop:
- Open the file for reading as bytes. Set
lastto LF, so that an empty file gives (0, 0). - Read a chunk of up to 64 KiB. If the read gives no bytes, the file is at its end.
- Add the number of LF bytes in the chunk to
newlines. Setlastto the last byte of the chunk. Go to step 2. - Return
newlines, andnewlines + 1iflastis not LF, elsenewlines.
- Python.
open(path, 'rb'). "Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding."3f.read(CHUNK)can return fewer bytes, and "An empty bytes object is returned if the stream is already at EOF."4chunk.count(b'\n')counts the LF bytes.5 A missing file raisesFileNotFoundError. - JavaScript and TypeScript (Node.js). A
for awaitloop overfs.createReadStream(path). The defaultencodingisnulland the defaulthighWaterMarkis 64 KiB, so each chunk is aBufferof up to 64 KiB.6chunk.indexOf(0x0a, i)finds the next LF. For a number, "value will be interpreted as an unsigned 8-bit integer value between 0 and 255", and the result is -1 "if buf does not contain value".7 A missing file rejects the loop with an error whosecodeisENOENT. The TypeScript file adds types only. - Java.
Files.newInputStream(path)in try-with-resources, andin.read(buf)in a loop. It returns "the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached."8 A missing file throwsNoSuchFileException. - C#.
File.OpenRead(path)andstream.Read(buffer). The result "can be less than the size of the buffer if that many bytes are not currently available, or zero (0) if the buffer's length is zero or the end of the stream has been reached."9buffer.AsSpan(0, n).Count((byte)'\n')"Counts the number of times the specified value occurs in the span."10 A missing file throwsFileNotFoundException. - Go.
Count(r io.Reader)holds the loop, andCountFileopens the file.bytes.Count(buf[:n], []byte{'\n'})counts the LF bytes: "Count counts the number of non-overlapping instances of sep in s."11 AReadcan return bytes and an error together. "Callers should always process the n > 0 bytes returned before considering the error err."12 So the loop counts the bytes first and then checks forio.EOF. A missing file gives an error for whicherrors.Is(err, fs.ErrNotExist)is true. - Rust.
count<R: Read>(r)holds the loop, andcount_linesopens the file.Ok(0)fromreadis the end of the file. "An error of the ErrorKind::Interrupted kind is non-fatal and the read operation should be retried if there is nothing else to do."13 So the loop reads again onInterrupted. A missing file gives an error of kindNotFound. - C.
fopenwith the moderb,freadinto a static buffer, andmemchrto find each LF. "fread does not distinguish between end-of-file and error, and callers must use feof and ferror to determine which occurred."14 So after the loop, the code callsferror. The counts areuintmax_t. On an error,count_linesreturns -1 anderrnotells why, for exampleENOENT. - C++.
std::ifstreamin binary mode,in.read(buf.data(), buf.size()), andstd::count. The last read stops at the end of the file with fewer bytes, and "The number of successfully extracted characters can be queried using gcount()."15std::count"Counts the elements that are equal to value".16 The function returnsstd::expected(C++23). - Bash.
wc -lwith the file on standard input gives newlines, and "no name shall be written".1tail -c 1on the file, piped towc -l, prints 1 if the last byte is LF, and 0 if it is not or the file is empty. Fortail -c, the number is "measured in bytes".17 A missing file gives a nonzero status and no output.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl, with one file for each in fixtures/. The result is (newlines, lines).
lf,blank-linesandcrlf: each line ends with LF or CRLF, so the two numbers are equal. An empty line is a line.empty: no bytes. The result is (0, 0), not (0, 1).only-newline: one empty line, so (1, 1).no-final-newline,one-line-no-newlineandcrlf-no-final-newline: the last line has no LF.one\ntwo\nthreegives (2, 3), andxgives (0, 1).cr-only:one\rtwo\rhas no LF, so it gives (0, 1). The file has one incomplete line.other-breaks: VT, FF, NEL and U+2028 in the middle of a line do not end it, so (1, 1).invalid-utf8andnul-bytes: the bytesFF FEand NUL bytes are counted as any other byte.
Each test file also writes a file of 100000 lines and the line end with no LF. The file is larger than one chunk of 64 KiB, and the result must be (100000, 100001). 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 this case by name.
Pitfalls
- Splitting the text gives the wrong count.
text.split('\n')gives one part more than the number of LF bytes, so a file that ends with LF has one line too many.str.splitlines()agrees with the LF count when each line ends with LF, because "a terminal line break does not result in an extra line".5 But "the boundaries are a superset of universal newlines".5 They include FF, NEL and U+2028, so a form feed in the text adds a line:
data = b"one\ntwo\n"
text = data.decode("utf-8")
print("split:", len(text.split("\n")))
print("splitlines:", len(text.splitlines()))
print("count:", data.count(b"\n"))
other = "page\fone\x85two\n"
print("splitlines:", len(other.splitlines()), "count:", other.count("\n"))
split: 3
splitlines: 2
count: 2
splitlines: 3 count: 1
Both methods also need the whole file in memory as decoded text. Count the LF bytes in chunks, as the solutions do.
- A loop over a text file sees CR as a line end. In text mode with the default
newline=None, "universal newlines mode is enabled", and a line can end with\r,\nor\r\n.3 So the lines that a loop gives are not the lines thatwc -lcounts:
import io
data = b"one\rtwo\r"
text_mode = io.TextIOWrapper(io.BytesIO(data), encoding="utf-8")
print("text mode:", sum(1 for _ in text_mode))
print("LF bytes:", data.count(b"\n"))
text mode: 2
LF bytes: 0
Text mode also decodes the bytes, so a byte that is not valid UTF-8 raises UnicodeDecodeError. Open the file in binary mode.
wc -ldoes not count a last line with no LF. It counts LF characters, not lines:1
printf 'one\ntwo\n' | wc -l
printf 'one\ntwo' | wc -l
2
1
If you need the incomplete line too, check the last byte, as the Bash solution does.
- The end of the read is not the end of the file. A read can return fewer bytes than the buffer holds, before the end of the file.49 Loop until the read gives no bytes (Python, C#, Rust, C), -1 (Java) or
io.EOF(Go). Do not stop when a chunk is shorter than the buffer. - Only the bytes that the read gave are counted. Count in
buf[:n], not in the whole buffer. After a short read, the end of the buffer still holds bytes of the chunk before it. - Reading the whole file in one call.
f.read(),fs.readFileSync,Files.readAllBytesandFile.ReadAllBytesput the whole file in memory. They are fine for small files, but they fail on a file that is larger than the memory.
Related tasks
- Read a file line by line: read each line as text, with the line terminator removed.
- Line ending: LF, CRLF and CR, and how programs change them.
- Read and write with buffers: read a file in chunks through a buffer.
- Read a binary file: read the bytes of a file without decoding them.
- Get the size of a file: get the number of bytes without reading them.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
"""Counts the lines of a file without decoding it."""
from os import PathLike
CHUNK = 64 * 1024
def count_lines(path: str | PathLike[str]) -> tuple[int, int]:
"""Returns (newlines, lines) for the file at path.
newlines is the number of LF bytes, the number that wc -l prints. lines
also counts a last line that has no LF. Raises OSError, for example
FileNotFoundError, if the file cannot be read.
"""
newlines = 0
last = b"\n" # an empty file has no line without an LF
with open(path, "rb") as f: # binary mode: no decoding, any bytes are accepted
while chunk := f.read(CHUNK):
newlines += chunk.count(b"\n")
last = chunk[-1:]
return newlines, newlines + (last != b"\n")
test_count_lines.py 52 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
from pathlib import Path
import pytest
from count_lines import CHUNK, count_lines
# name: (the bytes of the file, (newlines, lines))
CASES = {
"lf": (b"alpha\nbeta\ngamma\n", (3, 3)),
"blank-lines": (b"first\n\n\nlast\n", (4, 4)),
"empty": (b"", (0, 0)),
"only-newline": (b"\n", (1, 1)),
"no-final-newline": (b"one\ntwo\nthree", (2, 3)),
"one-line-no-newline": (b"x", (0, 1)),
"crlf": (b"one\r\ntwo\r\n", (2, 2)),
"crlf-no-final-newline": (b"one\r\ntwo", (1, 2)),
"cr-only": (b"one\rtwo\r", (0, 1)),
"other-breaks": ("a\vb\fc\x85d\u2028e\n".encode(), (1, 1)),
"invalid-utf8": (b"ok\n\xff\xfe\n", (2, 2)),
"nul-bytes": (b"a\x00b\n\x00\n", (2, 2)),
}
@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
data, want = CASES[name]
path = tmp_path / "input.txt"
path.write_bytes(data)
assert count_lines(path) == want
def test_many_chunks(tmp_path: Path) -> None:
# 100000 lines of 2 bytes and a last line with no LF: more than one chunk.
path = tmp_path / "input.txt"
path.write_bytes(b"x\n" * 100000 + b"end")
assert 2 * 100000 > CHUNK
assert count_lines(path) == (100000, 100001)
def test_lf_at_chunk_end(tmp_path: Path) -> None:
# The file ends with the LF that is the last byte of a full chunk.
path = tmp_path / "input.txt"
path.write_bytes(b"x" * (CHUNK - 1) + b"\n")
assert count_lines(path) == (1, 1)
def test_missing_file(tmp_path: Path) -> None:
with pytest.raises(FileNotFoundError):
count_lines(tmp_path / "missing.txt")
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
#include "count_lines.hpp"
#include <algorithm>
#include <array>
#include <fstream>
std::expected<LineCount, CountError> count_lines(const std::filesystem::path& path) {
// Binary mode: on Windows, text mode changes CRLF to LF.
std::ifstream in(path, std::ios::binary);
if (!in) {
return std::unexpected(CountError::cannot_open);
}
std::array<char, 64 * 1024> buf;
LineCount result;
char last = '\n'; // an empty file has no line without an LF
for (;;) {
in.read(buf.data(), buf.size());
// At the end of the file, read sets failbit and eofbit, and gcount gives the bytes it read.
const std::streamsize n = in.gcount();
if (n > 0) {
result.newlines += static_cast<std::uintmax_t>(std::count(buf.data(), buf.data() + n, '\n'));
last = buf[static_cast<std::size_t>(n - 1)];
}
if (in.eof()) {
break;
}
if (!in) {
return std::unexpected(CountError::read_failed);
}
}
if (in.bad()) {
return std::unexpected(CountError::read_failed);
}
result.lines = result.newlines + (last != '\n' ? 1 : 0);
return result;
}
count_lines.hpp 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
// since: C++23 (std::expected)
#pragma once
#include <cstdint>
#include <expected>
#include <filesystem>
struct LineCount {
std::uintmax_t newlines = 0; // the number of LF bytes, as wc -l prints it
std::uintmax_t lines = 0; // also counts a last line that has no LF
bool operator==(const LineCount&) const = default;
};
enum class CountError { cannot_open, read_failed };
// Counts the lines of the file at path. It reads the bytes and does not decode them.
std::expected<LineCount, CountError> count_lines(const std::filesystem::path& path);
test_count_lines.cpp 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
#include <cstdio>
#include <fstream>
#include <string>
#include <string_view>
#include <vector>
#include "count_lines.hpp"
using namespace std::string_literals;
namespace {
const std::filesystem::path input = "count_lines_input.txt";
struct test_case {
const char* name;
std::string data;
LineCount want;
};
} // namespace
int main() {
std::string many;
for (int i = 0; i < 100000; ++i) {
many += "x\n";
}
many += "end"; // more than one buffer of 64 KiB, and a last line with no LF
// The suffix s makes a std::string that keeps a NUL byte inside the literal.
const std::vector<test_case> cases = {
{"lf", "alpha\nbeta\ngamma\n", {3, 3}},
{"blank-lines", "first\n\n\nlast\n", {4, 4}},
{"empty", "", {0, 0}},
{"only-newline", "\n", {1, 1}},
{"no-final-newline", "one\ntwo\nthree", {2, 3}},
{"one-line-no-newline", "x", {0, 1}},
{"crlf", "one\r\ntwo\r\n", {2, 2}},
{"crlf-no-final-newline", "one\r\ntwo", {1, 2}},
{"cr-only", "one\rtwo\r", {0, 1}},
{"other-breaks", "a\vb\fc\xc2\x85" "d\xe2\x80\xa8" "e\n", {1, 1}},
{"invalid-utf8", "ok\n\xff\xfe\n", {2, 2}},
{"nul-bytes", "a\0b\n\0\n"s, {2, 2}},
{"many-chunks", many, {100000, 100001}},
};
int failures = 0;
for (const auto& c : cases) {
{
std::ofstream out(input, std::ios::binary);
out << c.data;
}
const auto got = count_lines(input);
if (!got || *got != c.want) {
std::fprintf(stderr, "case %s failed\n", c.name);
++failures;
}
}
std::filesystem::remove(input);
const auto missing = count_lines("count_lines_missing.txt");
if (missing || missing.error() != CountError::cannot_open) {
std::fprintf(stderr, "case missing failed\n");
++failures;
}
if (failures == 0) {
std::puts("ok");
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* The lines of a file. {@code newlines} is the number of LF bytes, the number that {@code wc -l}
* prints. {@code lines} also counts a last line that has no LF.
*/
public record LineCount(long newlines, long lines) {
/**
* Counts the lines of the file at path. It reads the bytes and does not decode them.
*
* @throws java.nio.file.NoSuchFileException if the file does not exist
* @throws IOException if the file cannot be read
*/
public static LineCount of(Path path) throws IOException {
byte[] buf = new byte[64 * 1024];
long newlines = 0;
byte last = '\n'; // an empty file has no line without an LF
try (InputStream in = Files.newInputStream(path)) {
int n;
while ((n = in.read(buf)) != -1) {
for (int i = 0; i < n; i++) {
if (buf[i] == '\n') {
newlines++;
}
}
if (n > 0) {
last = buf[n - 1];
}
}
}
return new LineCount(newlines, newlines + (last != '\n' ? 1 : 0));
}
}
LineCountTest.java 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.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 LineCountTest {
@TempDir Path dir;
private static Arguments text(String name, String data, long newlines, long lines) {
return Arguments.of(name, data.getBytes(StandardCharsets.UTF_8), newlines, lines);
}
static Stream<Arguments> cases() {
return Stream.of(
text("lf", "alpha\nbeta\ngamma\n", 3, 3),
text("blank-lines", "first\n\n\nlast\n", 4, 4),
text("empty", "", 0, 0),
text("only-newline", "\n", 1, 1),
text("no-final-newline", "one\ntwo\nthree", 2, 3),
text("one-line-no-newline", "x", 0, 1),
text("crlf", "one\r\ntwo\r\n", 2, 2),
text("crlf-no-final-newline", "one\r\ntwo", 1, 2),
text("cr-only", "one\rtwo\r", 0, 1),
text("other-breaks", "a\u000bb\fc\u0085d\u2028e\n", 1, 1),
Arguments.of("invalid-utf8", new byte[] {'o', 'k', '\n', (byte) 0xff, (byte) 0xfe, '\n'}, 2L, 2L),
text("nul-bytes", "a\0b\n\0\n", 2, 2),
// 100000 lines and a last line with no LF: more than one buffer of 64 KiB.
text("many-chunks", "x\n".repeat(100000) + "end", 100000, 100001));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void countLines(String name, byte[] data, long newlines, long lines) throws IOException {
Path path = Files.write(dir.resolve("input.txt"), data);
assertEquals(new LineCount(newlines, lines), LineCount.of(path));
}
@Test
void missingFile() {
assertThrows(NoSuchFileException.class, () -> LineCount.of(dir.resolve("missing.txt")));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
#include "count_lines.h"
#include <errno.h>
#include <stdio.h>
#include <string.h>
int count_lines(const char *path, uintmax_t *newlines, uintmax_t *lines) {
// "rb": on Windows, "r" would change CRLF to LF and stop at the byte 0x1A.
FILE *f = fopen(path, "rb");
if (f == NULL) {
return -1;
}
static char buf[64 * 1024];
uintmax_t count = 0;
char last = '\n'; // an empty file has no line without an LF
size_t n;
while ((n = fread(buf, 1, sizeof buf, f)) > 0) {
for (const char *p = buf, *end = buf + n; (p = memchr(p, '\n', (size_t)(end - p))) != NULL; p++) {
count++;
}
last = buf[n - 1];
}
// fread returns 0 both at the end of the file and on an error.
if (ferror(f)) {
int saved = errno;
fclose(f);
errno = saved != 0 ? saved : EIO;
return -1;
}
fclose(f);
*newlines = count;
*lines = count + (last != '\n');
return 0;
}
count_lines.h 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
#ifndef COUNT_LINES_H
#define COUNT_LINES_H
#include <stdint.h>
// count_lines reads the file at path as bytes. It stores the number of LF
// bytes in *newlines, the number that wc -l prints, and the number of lines in
// *lines, which also counts a last line that has no LF. It returns 0. On an
// error it returns -1, and errno holds the error of fopen or fread.
int count_lines(const char *path, uintmax_t *newlines, uintmax_t *lines);
#endif
test_count_lines.c 68 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
#include "count_lines.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char *path = "count_lines_input.txt";
static void write_file(const char *data, size_t n) {
FILE *f = fopen(path, "wb");
assert(f != NULL);
assert(fwrite(data, 1, n, f) == n);
assert(fclose(f) == 0);
}
static void check(const char *name, const char *data, size_t n, uintmax_t want_newlines, uintmax_t want_lines) {
write_file(data, n);
uintmax_t newlines = 99, lines = 99;
if (count_lines(path, &newlines, &lines) != 0 || newlines != want_newlines || lines != want_lines) {
fprintf(stderr, "case %s: got %ju, %ju\n", name, newlines, lines);
exit(1);
}
}
// sizeof counts the bytes of the literal, also a NUL byte inside it, but not the final NUL.
#define CASE(name, data, newlines, lines) check(name, data, sizeof(data) - 1, newlines, lines)
int main(void) {
CASE("lf", "alpha\nbeta\ngamma\n", 3, 3);
CASE("blank-lines", "first\n\n\nlast\n", 4, 4);
CASE("empty", "", 0, 0);
CASE("only-newline", "\n", 1, 1);
CASE("no-final-newline", "one\ntwo\nthree", 2, 3);
CASE("one-line-no-newline", "x", 0, 1);
CASE("crlf", "one\r\ntwo\r\n", 2, 2);
CASE("crlf-no-final-newline", "one\r\ntwo", 1, 2);
CASE("cr-only", "one\rtwo\r", 0, 1);
CASE("other-breaks", "a\vb\fc\xc2\x85" "d\xe2\x80\xa8" "e\n", 1, 1);
CASE("invalid-utf8", "ok\n\xff\xfe\n", 2, 2);
CASE("nul-bytes", "a\0b\n\0\n", 2, 2);
// 100000 lines and a last line with no LF: more than one buffer of 64 KiB.
size_t n = 2 * 100000 + 3;
char *big = malloc(n);
assert(big != NULL);
for (size_t i = 0; i < 100000; i++) {
big[2 * i] = 'x';
big[2 * i + 1] = '\n';
}
memcpy(big + 2 * 100000, "end", 3);
check("many-chunks", big, n, 100000, 100001);
free(big);
remove(path);
uintmax_t newlines, lines;
errno = 0;
if (count_lines("count_lines_missing.txt", &newlines, &lines) != -1 || errno != ENOENT) {
fprintf(stderr, "case missing: no ENOENT error\n");
return 1;
}
puts("ok");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
/// <summary>
/// The lines of a file. Newlines is the number of LF bytes, the number that wc -l prints.
/// Lines also counts a last line that has no LF.
/// </summary>
public readonly record struct LineCount(long Newlines, long Lines)
{
/// <summary>Counts the lines of the file at path. It reads the bytes and does not decode them.</summary>
/// <exception cref="FileNotFoundException">The file does not exist.</exception>
public static LineCount Read(string path)
{
var buffer = new byte[64 * 1024];
long newlines = 0;
byte last = (byte)'\n'; // an empty file has no line without an LF
using FileStream stream = File.OpenRead(path);
int n;
// Read returns 0 at the end of the file.
while ((n = stream.Read(buffer)) > 0)
{
newlines += buffer.AsSpan(0, n).Count((byte)'\n');
last = buffer[n - 1];
}
return new LineCount(newlines, newlines + (last != (byte)'\n' ? 1 : 0));
}
}
LineCountTests.cs 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
using System.Text;
using Xunit;
public sealed class LineCountTests : IDisposable
{
private readonly string dir = Directory.CreateTempSubdirectory("count-lines-").FullName;
public void Dispose() => Directory.Delete(dir, recursive: true);
private string Write(byte[] data)
{
string path = Path.Combine(dir, "input.txt");
File.WriteAllBytes(path, data);
return path;
}
public static TheoryData<string, string, long, long> Cases => new()
{
{ "lf", "alpha\nbeta\ngamma\n", 3, 3 },
{ "blank-lines", "first\n\n\nlast\n", 4, 4 },
{ "empty", "", 0, 0 },
{ "only-newline", "\n", 1, 1 },
{ "no-final-newline", "one\ntwo\nthree", 2, 3 },
{ "one-line-no-newline", "x", 0, 1 },
{ "crlf", "one\r\ntwo\r\n", 2, 2 },
{ "crlf-no-final-newline", "one\r\ntwo", 1, 2 },
{ "cr-only", "one\rtwo\r", 0, 1 },
{ "other-breaks", "a\vb\fc\u0085d\u2028e\n", 1, 1 },
{ "nul-bytes", "a\0b\n\0\n", 2, 2 },
// 100000 lines and a last line with no LF: more than one buffer of 64 KiB.
{ "many-chunks", string.Concat(Enumerable.Repeat("x\n", 100000)) + "end", 100000, 100001 },
};
[Theory]
[MemberData(nameof(Cases))]
public void CountsLines(string name, string text, long newlines, long lines)
{
Assert.False(string.IsNullOrEmpty(name));
Assert.Equal(new LineCount(newlines, lines), LineCount.Read(Write(Encoding.UTF8.GetBytes(text))));
}
[Fact]
public void InvalidUtf8() =>
Assert.Equal(new LineCount(2, 2), LineCount.Read(Write([0x6f, 0x6b, 0x0a, 0xff, 0xfe, 0x0a])));
[Fact]
public void MissingFile() =>
Assert.Throws<FileNotFoundException>(() => LineCount.Read(Path.Combine(dir, "missing.txt")));
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
import { createReadStream } from "node:fs";
const LF = 0x0a;
// Returns { newlines, lines } for the file at path. newlines is the number of
// LF bytes, the number that wc -l prints. lines also counts a last line that
// has no LF. The stream gives Buffers, because no encoding is set, so any bytes
// are accepted. A missing file rejects with an error whose code is "ENOENT".
export async function countLines(path) {
let newlines = 0;
let last = LF; // an empty file has no line without an LF
for await (const chunk of createReadStream(path)) {
for (let i = chunk.indexOf(LF); i !== -1; i = chunk.indexOf(LF, i + 1)) {
newlines++;
}
if (chunk.length > 0) {
last = chunk[chunk.length - 1];
}
}
return { newlines, lines: newlines + (last === LF ? 0 : 1) };
}
countLines.test.js 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";
import { countLines } from "./countLines.js";
// name: [the bytes of the file, newlines, lines]
const CASES = {
lf: ["alpha\nbeta\ngamma\n", 3, 3],
"blank-lines": ["first\n\n\nlast\n", 4, 4],
empty: ["", 0, 0],
"only-newline": ["\n", 1, 1],
"no-final-newline": ["one\ntwo\nthree", 2, 3],
"one-line-no-newline": ["x", 0, 1],
crlf: ["one\r\ntwo\r\n", 2, 2],
"crlf-no-final-newline": ["one\r\ntwo", 1, 2],
"cr-only": ["one\rtwo\r", 0, 1],
"other-breaks": [Buffer.from("a\vb\fc\u0085d\u2028e\n"), 1, 1],
"invalid-utf8": [Buffer.from([0x6f, 0x6b, 0x0a, 0xff, 0xfe, 0x0a]), 2, 2],
"nul-bytes": ["a\0b\n\0\n", 2, 2],
// 100000 lines and a last line with no LF: more than one chunk of 64 KiB.
"many-chunks": ["x\n".repeat(100000) + "end", 100000, 100001],
};
const dir = mkdtempSync(join(tmpdir(), "count-lines-"));
after(() => rmSync(dir, { recursive: true, force: true }));
for (const [name, [data, newlines, lines]] of Object.entries(CASES)) {
test(name, async () => {
const path = join(dir, `${name}.txt`);
writeFileSync(path, data);
assert.deepEqual(await countLines(path), { newlines, lines });
});
}
test("missing file", async () => {
await assert.rejects(countLines(join(dir, "missing.txt")), { code: "ENOENT" });
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
import { createReadStream } from "node:fs";
const LF = 0x0a;
export interface LineCount {
newlines: number; // the number of LF bytes, as wc -l prints it
lines: number; // also counts a last line that has no LF
}
// Counts the lines of the file at path without decoding it. The stream gives
// Buffers, because no encoding is set. A missing file rejects with an error
// whose code is "ENOENT".
export async function countLines(path: string): Promise<LineCount> {
let newlines = 0;
let last = LF; // an empty file has no line without an LF
for await (const chunk of createReadStream(path) as AsyncIterable<Buffer>) {
for (let i = chunk.indexOf(LF); i !== -1; i = chunk.indexOf(LF, i + 1)) {
newlines++;
}
if (chunk.length > 0) {
last = chunk[chunk.length - 1];
}
}
return { newlines, lines: newlines + (last === LF ? 0 : 1) };
}
countLines.test.ts 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";
import { countLines } from "./countLines.ts";
// name: [the bytes of the file, newlines, lines]
const CASES: Record<string, [string | Buffer, number, number]> = {
lf: ["alpha\nbeta\ngamma\n", 3, 3],
"blank-lines": ["first\n\n\nlast\n", 4, 4],
empty: ["", 0, 0],
"only-newline": ["\n", 1, 1],
"no-final-newline": ["one\ntwo\nthree", 2, 3],
"one-line-no-newline": ["x", 0, 1],
crlf: ["one\r\ntwo\r\n", 2, 2],
"crlf-no-final-newline": ["one\r\ntwo", 1, 2],
"cr-only": ["one\rtwo\r", 0, 1],
"other-breaks": [Buffer.from("a\vb\fc\u0085d\u2028e\n"), 1, 1],
"invalid-utf8": [Buffer.from([0x6f, 0x6b, 0x0a, 0xff, 0xfe, 0x0a]), 2, 2],
"nul-bytes": ["a\0b\n\0\n", 2, 2],
// 100000 lines and a last line with no LF: more than one chunk of 64 KiB.
"many-chunks": ["x\n".repeat(100000) + "end", 100000, 100001],
};
const dir = mkdtempSync(join(tmpdir(), "count-lines-"));
after(() => rmSync(dir, { recursive: true, force: true }));
for (const [name, [data, newlines, lines]] of Object.entries(CASES)) {
test(name, async () => {
const path = join(dir, `${name}.txt`);
writeFileSync(path, data);
assert.deepEqual(await countLines(path), { newlines, lines });
});
}
test("missing file", async () => {
await assert.rejects(countLines(join(dir, "missing.txt")), { code: "ENOENT" });
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
// Package countlines counts the lines of a file without decoding it.
package countlines
import (
"bytes"
"errors"
"io"
"os"
)
// Count returns the number of LF bytes in r, the number that wc -l prints,
// and the number of lines, which also counts a last line that has no LF.
func Count(r io.Reader) (newlines, lines int64, err error) {
buf := make([]byte, 64*1024)
last := byte('\n') // an empty input has no line without an LF
for {
n, err := r.Read(buf)
// Process the bytes first: Read can return n > 0 together with an error.
if n > 0 {
newlines += int64(bytes.Count(buf[:n], []byte{'\n'}))
last = buf[n-1]
}
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return 0, 0, err
}
}
lines = newlines
if last != '\n' {
lines++
}
return newlines, lines, nil
}
// CountFile counts the lines of the file at path. A missing file gives an
// error for which errors.Is(err, fs.ErrNotExist) is true.
func CountFile(path string) (newlines, lines int64, err error) {
f, err := os.Open(path)
if err != nil {
return 0, 0, err
}
defer f.Close()
return Count(f)
}
count_lines_test.go 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
package countlines
import (
"errors"
"io/fs"
"os"
"path/filepath"
"strings"
"testing"
)
var cases = []struct {
name string
data string
newlines, lines int64
}{
{"lf", "alpha\nbeta\ngamma\n", 3, 3},
{"blank-lines", "first\n\n\nlast\n", 4, 4},
{"empty", "", 0, 0},
{"only-newline", "\n", 1, 1},
{"no-final-newline", "one\ntwo\nthree", 2, 3},
{"one-line-no-newline", "x", 0, 1},
{"crlf", "one\r\ntwo\r\n", 2, 2},
{"crlf-no-final-newline", "one\r\ntwo", 1, 2},
{"cr-only", "one\rtwo\r", 0, 1},
{"other-breaks", "a\vb\fc\u0085d\u2028e\n", 1, 1},
{"invalid-utf8", "ok\n\xff\xfe\n", 2, 2},
{"nul-bytes", "a\x00b\n\x00\n", 2, 2},
// 100000 lines and a last line with no LF: more than one buffer of 64 KiB.
{"many-chunks", strings.Repeat("x\n", 100000) + "end", 100000, 100001},
}
func TestCountFile(t *testing.T) {
dir := t.TempDir()
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
path := filepath.Join(dir, c.name+".txt")
if err := os.WriteFile(path, []byte(c.data), 0o644); err != nil {
t.Fatal(err)
}
newlines, lines, err := CountFile(path)
if err != nil || newlines != c.newlines || lines != c.lines {
t.Fatalf("CountFile = %d, %d, %v; want %d, %d", newlines, lines, err, c.newlines, c.lines)
}
})
}
}
func TestMissingFile(t *testing.T) {
_, _, err := CountFile(filepath.Join(t.TempDir(), "missing.txt"))
if !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("err = %v; want fs.ErrNotExist", err)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
//! Counts the lines of a file without decoding it.
use std::fs::File;
use std::io::{self, ErrorKind, Read};
use std::path::Path;
/// Returns `(newlines, lines)` for the bytes of `r`. `newlines` is the number of
/// LF bytes, the number that `wc -l` prints. `lines` also counts a last line that
/// has no LF.
pub fn count<R: Read>(mut r: R) -> io::Result<(u64, u64)> {
let mut buf = vec![0u8; 64 * 1024];
let mut newlines = 0u64;
let mut last = b'\n'; // an empty input has no line without an LF
loop {
let n = match r.read(&mut buf) {
Ok(0) => break,
Ok(n) => n,
// A signal stopped the read before it read a byte: read again.
Err(e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => return Err(e),
};
newlines += buf[..n].iter().filter(|&&b| b == b'\n').count() as u64;
last = buf[n - 1];
}
Ok((newlines, newlines + u64::from(last != b'\n')))
}
/// Counts the lines of the file at `path`. A missing file gives an error of
/// kind `NotFound`.
pub fn count_lines(path: impl AsRef<Path>) -> io::Result<(u64, u64)> {
count(File::open(path)?)
}
tests/count_lines_test.rs 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;
use algo_count_the_lines_of_a_file::count_lines;
/// Writes the bytes to a new file in the temporary directory and returns its path.
fn write(name: &str, data: &[u8]) -> PathBuf {
let dir = std::env::temp_dir().join(format!("count-lines-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
let path = dir.join(name);
fs::write(&path, data).unwrap();
path
}
const CASES: &[(&str, &[u8], u64, u64)] = &[
("lf", b"alpha\nbeta\ngamma\n", 3, 3),
("blank-lines", b"first\n\n\nlast\n", 4, 4),
("empty", b"", 0, 0),
("only-newline", b"\n", 1, 1),
("no-final-newline", b"one\ntwo\nthree", 2, 3),
("one-line-no-newline", b"x", 0, 1),
("crlf", b"one\r\ntwo\r\n", 2, 2),
("crlf-no-final-newline", b"one\r\ntwo", 1, 2),
("cr-only", b"one\rtwo\r", 0, 1),
("other-breaks", "a\x0bb\x0cc\u{85}d\u{2028}e\n".as_bytes(), 1, 1),
("invalid-utf8", b"ok\n\xff\xfe\n", 2, 2),
("nul-bytes", b"a\0b\n\0\n", 2, 2),
];
#[test]
fn cases() {
for (name, data, newlines, lines) in CASES {
let path = write(name, data);
assert_eq!(count_lines(&path).unwrap(), (*newlines, *lines), "{name}");
fs::remove_file(&path).unwrap();
}
}
#[test]
fn many_chunks() {
// 100000 lines and a last line with no LF: more than one buffer of 64 KiB.
let mut data = b"x\n".repeat(100_000);
data.extend_from_slice(b"end");
let path = write("many-chunks", &data);
assert_eq!(count_lines(&path).unwrap(), (100_000, 100_001));
fs::remove_file(&path).unwrap();
}
#[test]
fn missing_file() {
let err = count_lines(std::env::temp_dir().join("count-lines-missing.txt")).unwrap_err();
assert_eq!(err.kind(), ErrorKind::NotFound);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
# count_lines PATH
# Prints "NEWLINES LINES": the number of LF bytes, as wc -l counts them, and the
# number of lines, which also counts a last line that has no LF.
# Returns a nonzero status, and prints nothing on stdout, if the file cannot be read.
count_lines() {
local newlines last
# With the file on stdin, wc prints no file name.
newlines=$(wc -l <"$1") || return
# The last byte of the file: 1 if it is an LF, 0 if it is not or the file is empty.
last=$(tail -c 1 -- "$1" | wc -l) || return
# $((...)) also accepts blanks around a number.
newlines=$((newlines))
if [[ -s $1 ]] && ((last == 0)); then
printf '%d %d\n' "$newlines" "$((newlines + 1))"
else
printf '%d %d\n' "$newlines" "$newlines"
fi
}
test_count_lines.bats 43 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-lines-of-a-file/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/count_lines.sh"
file="$BATS_TEST_TMPDIR/input.txt"
}
check() { # check BYTES WANT
printf '%b' "$1" >"$file"
run count_lines "$file"
[ "$status" -eq 0 ]
[ "$output" = "$2" ]
}
@test "lf" { check 'alpha\nbeta\ngamma\n' "3 3"; }
@test "blank-lines" { check 'first\n\n\nlast\n' "4 4"; }
@test "empty" { check '' "0 0"; }
@test "only-newline" { check '\n' "1 1"; }
@test "no-final-newline" { check 'one\ntwo\nthree' "2 3"; }
@test "one-line-no-newline" { check 'x' "0 1"; }
@test "crlf" { check 'one\r\ntwo\r\n' "2 2"; }
@test "crlf-no-final-newline" { check 'one\r\ntwo' "1 2"; }
@test "cr-only" { check 'one\rtwo\r' "0 1"; }
@test "other-breaks" { check 'a\vb\fc\xc2\x85d\xe2\x80\xa8e\n' "1 1"; }
@test "invalid-utf8" { check 'ok\n\xff\xfe\n' "2 2"; }
@test "nul-bytes" { check 'a\0b\n\0\n' "2 2"; }
@test "many-chunks" {
{ yes x | head -n 100000; printf 'end'; } >"$file"
run count_lines "$file"
[ "$status" -eq 0 ]
[ "$output" = "100000 100001" ]
}
@test "missing" {
run --separate-stderr count_lines "$BATS_TEST_TMPDIR/missing.txt"
[ "$status" -ne 0 ]
[ -z "$output" ]
}
References
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), wc, DESCRIPTION; OPTIONS (-l); STDOUT
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), Base Definitions, Chapter 3: Definitions, 3.172 Incomplete Line; 3.185 Line
- The Python Standard Library, Built-in Functions, open(), the mode 'b' and the newline parameter
- The Python Standard Library, io, BufferedIOBase.read
- The Python Standard Library, Built-in Types, bytes.count; str.splitlines
- Node.js documentation, File system, fs.createReadStream(path[, options])
- Node.js documentation, Buffer, buf.indexOf(value[, byteOffset][, encoding])
- Java SE 25 API, java.io.InputStream, read(byte[])
- .NET API reference, Stream.Read, Read(Span<Byte>), Returns
- .NET API reference, MemoryExtensions.Count, Count<T>(Span<T>, T)
- Go standard library, package bytes, func Count
- Go standard library, package io, type Reader
- The Rust Standard Library, std::io::Read, Read::read, Errors
- cppreference.com, fread, Return value
- cppreference.com, std::basic_istream::read, description
- cppreference.com, std::count, description, overload (1)
- The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), tail, OPTIONS (-c)
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 87Y514 Edit this page History Report an error Markdown