Taskcore
Read from standard input
Also called read stdin, read input line by line, read all of standard input, read until end of input.
Read the standard input of the process to the end of input, line by line, and return each line without its newline or CRLF.
- Evidence
- Code in 10 languages
Task
Read the standard input of the process to the end of input. Return the lines in order.
Each solution is a function read_lines() that returns a list of strings. A line ends with LF ("\n") or CRLF ("\r\n"), and the line in the result has no terminator. A last line with no newline is also a line. An empty input gives an empty list.
Standard input is file descriptor 0. It is open for reading when the program starts. The shell connects it to a terminal, a file (prog < file) or a pipe (a | prog). The program reads it in the same way in each case. The end of input is a read that returns zero bytes. For a file, this occurs at the end of the file. For a pipe, it occurs when the pipe is empty and no process has it open for writing.
The tests control the input. Each test writes the bytes of a case to a file or a pipe and makes it the standard input of the call. The cases are UTF-8 text.
Solutions
There are two ways to read standard input. Read all of it at once, and then split it. Or read one line at a time until the end of input. The first way keeps all of the input in memory. The second way keeps only one line, so it also works on input that is larger than memory, and on input that never ends. The solutions use the second way.
The two examples read the same input:
alpha
beta
gamma
All of the input at once:
import sys
text = sys.stdin.read()
print(repr(text))
print(text.splitlines())
'alpha\nbeta\ngamma\n'
['alpha', 'beta', 'gamma']
One line at a time, until the end of input:
import sys
for number, line in enumerate(sys.stdin, start=1):
print(number, line.removesuffix("\n"))
1 alpha
2 beta
3 gamma
- Python.
for line in sys.stdinreads one line at a time and stops at the end of input. Each line keeps its"\n", so the solution removes it, and also a"\r"before it.sys.stdinis a text file, and its default encoding depends on the platform. The solution callssys.stdin.reconfigure(encoding="utf-8"), which must come before the first read.sys.stdin.read()reads all of the input. - JavaScript and TypeScript (Node.js).
readline.createInterface({ input: process.stdin, crlfDelay: Infinity })and afor awaitloop. WithcrlfDelay: Infinity,"\r\n"is always one line break. The loop ends when the stream ends.setEncoding("utf8")decodes a character correctly also when two chunks split its bytes. To read all of the input, usetext(process.stdin)fromnode:stream/consumers. The TypeScript file adds types only. - Java.
new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)).readLinereturns the line without"\n","\r"or"\r\n", and returnsnullat the end of the stream. The documentation ofSystem.intells you to decode with the encoding in thestdin.encodingproperty. The contract says UTF-8, so the solution names UTF-8. The test replacesSystem.inwithSystem.setIn. - C#.
Console.Inis aTextReaderfor standard input.ReadLinereturnsnullwhen all of the characters are read. A final newline does not give an extra empty line. The test replaces the reader withConsole.SetIn. - Go. A
bufio.Scanneronos.Stdin.Scanreturns false at the end of input, andTextgives the line without"\n"or"\r\n". After the loop,Errtells an error apart from the end of input. The solution raises the line limit of the scanner, as Read a file line by line explains.io.ReadAll(os.Stdin)reads all of the input, and returns a nil error at the end of input, notio.EOF. - Rust.
io::stdin().lock()gives a reader that implementsBufRead, andlines()gives each line without"\n"or"\r\n". A line that is not valid UTF-8 gives an error.read_linekeeps the newline, and returnsOk(0)at the end of input.read_to_stringreads all of the input. - C.
getline(&line, &size, stdin)reads one line into a buffer that it allocates. It keeps the"\n", so the solution removes it and a"\r". It returns -1 at the end of input and on an error, soferrortells the two apart.getlineis POSIX, not ISO C, so the file defines_POSIX_C_SOURCE. - C++.
std::getline(std::cin, line)in awhileloop. It removes the'\n', but it does not remove a'\r', so the solution removes it. The loop stops whengetlineextracts no character. - Bash.
while IFS= read -r line || [[ -n $line ]].IFS=keeps blanks at the start and end of a line, and-rkeeps backslashes.readreturns a status that is not zero at the end of file. The test[[ -n $line ]]keeps a last line with no newline, as Read a file line by line explains. The solution removes a"\r"at the end of a line, and puts the lines in the global arraylines.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl. Each case gives the bytes on standard input (stdin) and the lines that the solution must return.
empty: no bytes. The result is[].only-newline: one"\n"is one empty line, so the result is[""].trailing-blank-line:"last\n\n"gives["last", ""]. The final newline does not add a line, but the empty line before it is a line.no-final-newlineandcrlf-no-final-newline: the last line has no terminator, and it is still a line.crlfandmixed-endings:"\r\n"ends a line, and the"\r"is not part of the line.whitespaceandbackslashes: the line comes back with no change. In Bash, this needsIFS=and-r.non-ascii: UTF-8 characters of 2, 3 and 4 bytes.long-line: only in the native tests. It is a line of 1 MiB. The default buffer of a Gobufio.Scannerstops at 64 KiB.
Pitfalls
input()at the end of input. In Python,input()raisesEOFErrorat the end of input. A loop that calls it without a stop condition fails after the last line:
This code raises EOFError, on purpose.
while True:
line = input()
print(line.upper())
ALPHA
BETA
GAMMA
Use for line in sys.stdin, or catch EOFError.
- Lost trailing newlines in Bash. Command substitution deletes the trailing newlines of the output. So
$(cat)changes the input:
This code runs but gives a wrong answer on purpose.
text=$(cat)
printf '%q\n' "$text"
$'alpha\nbeta\ngamma'
The difference is important when the program writes the text again, or counts its bytes. To read the lines, use the read loop of the solution.
- A loop on the right side of a pipe. Each command of a pipeline runs in its own subshell. A variable that the loop sets is lost when the loop ends. Redirect the input into the loop instead:
count=0
printf 'a\nb\nc\n' | while IFS= read -r line; do
count=$((count + 1))
done
echo "after the pipe: $count"
count=0
while IFS= read -r line; do
count=$((count + 1))
done < <(printf 'a\nb\nc\n')
echo "after the redirection: $count"
after the pipe: 0
after the redirection: 3
- An extra empty line after a split. Text that ends with a newline gives an empty string at the end when you split it on
"\n":
This code runs but gives a wrong answer on purpose.
import { text } from "node:stream/consumers";
const data = await text(process.stdin);
console.log(JSON.stringify(data.split("\n")));
["alpha","beta","gamma",""]
A split on "\n" also keeps the "\r" of CRLF input. Use the readline loop of the solution.
The next two pitfalls read this input:
2
Ada Lovelace
nextLineafternextIntin Java.nextIntreads the number and stops before the newline.nextLinethen returns the rest of that line, which is empty:
This code runs but gives a wrong answer on purpose.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = in.nextInt();
String name = in.nextLine();
System.out.println(count + " [" + name + "]");
}
}
2 []
Read each line with nextLine, and then parse the number with Integer.parseInt.
fmt.Scanreads words, not lines. In Go,fmt.Scantreats newlines as spaces, and a string ends at the first space:
This code runs but gives a wrong answer on purpose.
package main
import "fmt"
func main() {
var count int
var name string
fmt.Scan(&count, &name)
fmt.Printf("%d [%s]\n", count, name)
}
2 [Ada]
Use a bufio.Scanner to read lines.
- The end of input on a terminal. When standard input is a terminal, a read waits until the user types a whole line. A program that reads to the end of input waits until the user types the EOF character. The Node.js documentation gives Ctrl+D for it. If the line has bytes, the EOF character sends them to the program without a newline, and the input does not end. At the start of a line, the read returns zero bytes, and this is the end of input. So type Ctrl+D at the start of a line, or type it two times. On Windows, the .NET documentation gives Ctrl+Z, then Enter. A program that waits with no prompt can look as if it stopped, so show a prompt, or read from a file or a pipe.
Related tasks
- Read a file line by line: the same loop on a file, with the checks for UTF-8.
- Parse command-line arguments: by the POSIX guidelines, the operand
-means standard input. - Run a subprocess: give a child process its standard input.
- Read an environment variable: another input that a program gets from its parent.
- Write a file: the output side.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-from-standard-input/.
import io
import sys
from typing import TextIO
def read_lines(stream: TextIO | None = None) -> list[str]:
"""Read a text stream to its end and return its lines without "\\n" or "\\r\\n".
The default stream is standard input, decoded as UTF-8.
"""
if stream is None:
# The default encoding of sys.stdin comes from the locale.
# reconfigure must come before the first read.
if isinstance(sys.stdin, io.TextIOWrapper):
sys.stdin.reconfigure(encoding="utf-8")
stream = sys.stdin
lines = []
# The loop reads one line at a time and stops at the end of input.
for line in stream:
lines.append(line.removesuffix("\n").removesuffix("\r"))
return lines
if __name__ == "__main__":
for line in read_lines():
print(line)
test_read_lines.py 58 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-from-standard-input/.
import io
import json
import subprocess
import sys
from pathlib import Path
import pytest
from read_lines import read_lines
CASES = {
"lf": (b"alpha\nbeta\ngamma\n", ["alpha", "beta", "gamma"]),
"blank-lines": (b"first\n\n\nlast line\n", ["first", "", "", "last line"]),
"empty": (b"", []),
"only-newline": (b"\n", [""]),
"no-final-newline": (b"one\ntwo\nthree", ["one", "two", "three"]),
"crlf": (b"one\r\ntwo\r\nthree\r\n", ["one", "two", "three"]),
"crlf-no-final-newline": (b"one\r\ntwo\r\nthree", ["one", "two", "three"]),
"mixed-endings": (b"one\r\ntwo\nthree\r\n", ["one", "two", "three"]),
"trailing-blank-line": (b"last\n\n", ["last", ""]),
"whitespace": (b" two spaces\ttab \n", [" two spaces\ttab "]),
"backslashes": (b"C:\\temp\\new\n", ["C:\\temp\\new"]),
"non-ascii": (
"naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n".encode(),
["naïve café", "日本語のテキスト", "🙂🙂🙂🙂🙂🙂"],
),
"long-line": (b"x" * (1 << 20) + b"\nend\n", ["x" * (1 << 20), "end"]),
}
# The child process prints the result as JSON, so the test can compare it.
CHILD = "import json, read_lines; print(json.dumps(read_lines.read_lines()))"
@pytest.mark.parametrize("name", CASES)
def test_stdin(name: str) -> None:
data, want = CASES[name]
# pytest replaces sys.stdin, so a child process reads the real standard input.
# LC_ALL=C makes the default encoding of the child ASCII, so the test also checks reconfigure.
result = subprocess.run(
[sys.executable, "-c", CHILD],
input=data,
capture_output=True,
check=True,
cwd=Path(__file__).parent,
env={"LC_ALL": "C", "PYTHONUTF8": "0"},
)
assert json.loads(result.stdout) == want
@pytest.mark.parametrize("name", CASES)
def test_stream(name: str) -> None:
data, want = CASES[name]
# newline="" keeps "\r\n", as sys.stdin does on a pipe.
stream = io.TextIOWrapper(io.BytesIO(data), encoding="utf-8", newline="")
assert read_lines(stream) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
#include "read_lines.hpp"
#include <ios>
std::vector<std::string> read_lines(std::istream& in) {
std::vector<std::string> lines;
std::string line;
// getline removes the '\n'. It fails when no character is left.
while (std::getline(in, line)) {
if (line.ends_with('\r')) line.pop_back();
lines.push_back(line);
}
// badbit means a read error; eofbit and failbit alone mean the end of input.
if (in.bad()) throw std::ios_base::failure("read_lines: read error");
return lines;
}
read_lines.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
#pragma once
#include <iostream>
#include <string>
#include <vector>
// Reads the stream to its end and returns its lines, each without "\n" or "\r\n".
// The default stream is standard input. A read error throws std::ios_base::failure.
std::vector<std::string> read_lines(std::istream& in = std::cin);
test_read_lines.cpp 72 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>
#include "read_lines.hpp"
namespace {
const std::filesystem::path input = "read_lines_input.txt";
int failures = 0;
void check(std::string_view name, bool ok) {
if (!ok) {
std::fprintf(stderr, "case %.*s failed\n", static_cast<int>(name.size()), name.data());
++failures;
}
}
} // namespace
int main() {
struct Case {
std::string name, data;
std::vector<std::string> want;
};
const std::string long_line(1 << 20, 'x');
const std::vector<Case> cases = {
{"lf", "alpha\nbeta\ngamma\n", {"alpha", "beta", "gamma"}},
{"blank-lines", "first\n\n\nlast line\n", {"first", "", "", "last line"}},
{"empty", "", {}},
{"only-newline", "\n", {""}},
{"no-final-newline", "one\ntwo\nthree", {"one", "two", "three"}},
{"crlf", "one\r\ntwo\r\nthree\r\n", {"one", "two", "three"}},
{"crlf-no-final-newline", "one\r\ntwo\r\nthree", {"one", "two", "three"}},
{"mixed-endings", "one\r\ntwo\nthree\r\n", {"one", "two", "three"}},
{"trailing-blank-line", "last\n\n", {"last", ""}},
{"whitespace", " two spaces\ttab \n", {" two spaces\ttab "}},
{"backslashes", "C:\\temp\\new\n", {"C:\\temp\\new"}},
{"non-ascii",
"naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n",
{"naïve café", "日本語のテキスト", "🙂🙂🙂🙂🙂🙂"}},
{"long-line", long_line + "\nend\n", {long_line, "end"}},
};
for (const auto& c : cases) {
std::istringstream in(c.data);
check(c.name, read_lines(in) == c.want);
// The same case on the real standard input. std::cin reads through
// the C stream stdin, so freopen gives it the new file.
{
std::ofstream out(input, std::ios::binary);
out << c.data;
}
if (std::freopen(input.c_str(), "rb", stdin) == nullptr) return EXIT_FAILURE;
std::cin.clear(); // clears the eofbit of the case before
check(c.name, read_lines() == c.want);
}
std::filesystem::remove(input);
if (failures > 0) return EXIT_FAILURE;
std::puts("all cases pass");
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/** Reads the lines of standard input. */
public final class ReadLines {
private ReadLines() {}
/** Reads the stream to its end and returns its lines, each without "\n" or "\r\n". */
public static List<String> readLines(InputStream in) throws IOException {
// The code does not close the reader, because that also closes the stream.
BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
List<String> lines = new ArrayList<>();
// readLine returns null at the end of the stream.
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
lines.add(line);
}
return lines;
}
/** Reads standard input to its end and returns its lines. */
public static List<String> readStdinLines() throws IOException {
return readLines(System.in);
}
}
ReadLinesTest.java 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class ReadLinesTest {
private static Arguments text(String name, String data, String... want) {
return Arguments.of(name, data.getBytes(StandardCharsets.UTF_8), List.of(want));
}
static Stream<Arguments> cases() {
String longLine = "x".repeat(1 << 20);
return Stream.of(
text("lf", "alpha\nbeta\ngamma\n", "alpha", "beta", "gamma"),
text("blank-lines", "first\n\n\nlast line\n", "first", "", "", "last line"),
text("empty", ""),
text("only-newline", "\n", ""),
text("no-final-newline", "one\ntwo\nthree", "one", "two", "three"),
text("crlf", "one\r\ntwo\r\nthree\r\n", "one", "two", "three"),
text("crlf-no-final-newline", "one\r\ntwo\r\nthree", "one", "two", "three"),
text("mixed-endings", "one\r\ntwo\nthree\r\n", "one", "two", "three"),
text("trailing-blank-line", "last\n\n", "last", ""),
text("whitespace", " two spaces\ttab \n", " two spaces\ttab "),
text("backslashes", "C:\\temp\\new\n", "C:\\temp\\new"),
text(
"non-ascii",
"naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n",
"naïve café",
"日本語のテキスト",
"🙂🙂🙂🙂🙂🙂"),
text("long-line", longLine + "\nend\n", longLine, "end"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void readsStandardInput(String name, byte[] data, List<String> want) throws IOException {
InputStream saved = System.in;
System.setIn(new ByteArrayInputStream(data));
try {
assertEquals(want, ReadLines.readStdinLines(), name);
} finally {
System.setIn(saved);
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
// getline is in POSIX.1-2008, not in ISO C.
#define _POSIX_C_SOURCE 200809L
#include "read_lines.h"
#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>
void free_lines(char **lines, size_t count) {
for (size_t i = 0; i < count; i++) free(lines[i]);
free(lines);
}
int read_lines(FILE *stream, char ***lines, size_t *count) {
char **out = NULL;
size_t n = 0, cap = 0;
for (;;) {
char *line = NULL;
size_t size = 0;
errno = 0;
// getline returns -1 at the end of input and on an error.
ssize_t len = getline(&line, &size, stream);
if (len == -1) {
free(line);
break;
}
if (len > 0 && line[len - 1] == '\n') line[--len] = '\0';
if (len > 0 && line[len - 1] == '\r') line[--len] = '\0';
if (n == cap) {
size_t new_cap = cap == 0 ? 16 : cap * 2;
char **grown = realloc(out, new_cap * sizeof *grown);
if (grown == NULL) {
free(line);
free_lines(out, n);
return -1;
}
out = grown;
cap = new_cap;
}
out[n++] = line;
}
// feof tells the end of input apart from an error.
if (ferror(stream)) {
int err = errno != 0 ? errno : EIO;
free_lines(out, n);
errno = err;
return -1;
}
*lines = out;
*count = n;
return 0;
}
read_lines.h 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
#ifndef READ_LINES_H
#define READ_LINES_H
#include <stddef.h>
#include <stdio.h>
// read_lines reads stream to its end. It stores a new array of *count lines
// in *lines and returns 0. Each line is a string without its "\n" or "\r\n".
// On a read error or when memory runs out, it returns -1 and sets errno.
// Free the result with free_lines. Pass stdin to read standard input.
int read_lines(FILE *stream, char ***lines, size_t *count);
// free_lines frees the array of read_lines and each of its lines.
void free_lines(char **lines, size_t count);
#endif
test_read_lines.c 74 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
#include "read_lines.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char *path = "read_lines_input.txt";
static int failures = 0;
// check writes the data to a file, makes the file the standard input and
// compares the lines with want, an array that ends with NULL.
static void check(const char *name, const char *data, size_t n, const char *const *want) {
FILE *f = fopen(path, "wb");
assert(f != NULL);
assert(fwrite(data, 1, n, f) == n);
assert(fclose(f) == 0);
assert(freopen(path, "rb", stdin) != NULL);
char **lines;
size_t count;
if (read_lines(stdin, &lines, &count) != 0) {
fprintf(stderr, "case %s: read_lines failed\n", name);
failures++;
return;
}
size_t i = 0;
for (; want[i] != NULL; i++) {
if (i >= count || strcmp(lines[i], want[i]) != 0) break;
}
if (want[i] != NULL || i != count) {
fprintf(stderr, "case %s: got %zu lines, line %zu differs\n", name, count, i);
failures++;
}
free_lines(lines, count);
}
#define CASE(name, data, ...) check(name, data, sizeof(data) - 1, (const char *const[]){__VA_ARGS__})
int main(void) {
CASE("lf", "alpha\nbeta\ngamma\n", "alpha", "beta", "gamma", NULL);
CASE("blank-lines", "first\n\n\nlast line\n", "first", "", "", "last line", NULL);
CASE("empty", "", NULL);
CASE("only-newline", "\n", "", NULL);
CASE("no-final-newline", "one\ntwo\nthree", "one", "two", "three", NULL);
CASE("crlf", "one\r\ntwo\r\nthree\r\n", "one", "two", "three", NULL);
CASE("crlf-no-final-newline", "one\r\ntwo\r\nthree", "one", "two", "three", NULL);
CASE("mixed-endings", "one\r\ntwo\nthree\r\n", "one", "two", "three", NULL);
CASE("trailing-blank-line", "last\n\n", "last", "", NULL);
CASE("whitespace", " two spaces\ttab \n", " two spaces\ttab ", NULL);
CASE("backslashes", "C:\\temp\\new\n", "C:\\temp\\new", NULL);
CASE("non-ascii", "naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n", "naïve café", "日本語のテキスト",
"🙂🙂🙂🙂🙂🙂", NULL);
size_t n = (size_t)1 << 20;
char *data = malloc(n + 5);
char *line = malloc(n + 1);
assert(data != NULL && line != NULL);
memset(data, 'x', n);
memcpy(data + n, "\nend\n", 5);
memcpy(line, data, n);
line[n] = '\0';
check("long-line", data, n + 5, (const char *const[]){line, "end", NULL});
free(line);
free(data);
remove(path);
if (failures > 0) return 1;
puts("all cases pass");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
/// <summary>Reads the lines of standard input.</summary>
public static class StdinLines
{
/// <summary>Reads the reader to its end and returns its lines, each without "\n" or "\r\n".</summary>
public static List<string> ReadLines(TextReader reader)
{
var lines = new List<string>();
// ReadLine returns null at the end of the input.
while (reader.ReadLine() is string line)
{
lines.Add(line);
}
return lines;
}
/// <summary>Reads standard input to its end and returns its lines.</summary>
public static List<string> ReadStdinLines() => ReadLines(Console.In);
}
StdinLinesTests.cs 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
using System.Text;
using Xunit;
public sealed class StdinLinesTests
{
private static readonly string LongLine = new('x', 1 << 20);
public static TheoryData<string, string, string[]> Cases => new()
{
{ "lf", "alpha\nbeta\ngamma\n", ["alpha", "beta", "gamma"] },
{ "blank-lines", "first\n\n\nlast line\n", ["first", "", "", "last line"] },
{ "empty", "", [] },
{ "only-newline", "\n", [""] },
{ "no-final-newline", "one\ntwo\nthree", ["one", "two", "three"] },
{ "crlf", "one\r\ntwo\r\nthree\r\n", ["one", "two", "three"] },
{ "crlf-no-final-newline", "one\r\ntwo\r\nthree", ["one", "two", "three"] },
{ "mixed-endings", "one\r\ntwo\nthree\r\n", ["one", "two", "three"] },
{ "trailing-blank-line", "last\n\n", ["last", ""] },
{ "whitespace", " two spaces\ttab \n", [" two spaces\ttab "] },
{ "backslashes", "C:\\temp\\new\n", ["C:\\temp\\new"] },
{ "non-ascii", "naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n", ["naïve café", "日本語のテキスト", "🙂🙂🙂🙂🙂🙂"] },
{ "long-line", LongLine + "\nend\n", [LongLine, "end"] },
};
[Theory]
[MemberData(nameof(Cases))]
public void ReadsStandardInput(string name, string text, string[] want)
{
Assert.False(string.IsNullOrEmpty(name));
TextReader saved = Console.In;
// The test gives the bytes to a UTF-8 reader and makes it the standard input.
Console.SetIn(new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(text)), Encoding.UTF8));
try
{
Assert.Equal(want, StdinLines.ReadStdinLines());
}
finally
{
Console.SetIn(saved);
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
import { createInterface } from "node:readline";
/**
* Reads a stream to its end and returns its lines without "\n" or "\r\n".
* @param {import("node:stream").Readable} [input] standard input by default
* @returns {Promise<string[]>}
*/
export async function readLines(input = process.stdin) {
// Decode the bytes as UTF-8, also when a character is split between two chunks.
input.setEncoding("utf8");
// crlfDelay: Infinity makes "\r\n" one line break even when a chunk ends between "\r" and "\n".
const reader = createInterface({ input, crlfDelay: Infinity });
const lines = [];
// The loop ends when the stream ends.
for await (const line of reader) {
lines.push(line);
}
return lines;
}
readLines.test.js 56 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { Readable } from "node:stream";
import { test } from "node:test";
import { readLines } from "./readLines.js";
const long = "x".repeat(1 << 20);
const cases = [
["lf", "alpha\nbeta\ngamma\n", ["alpha", "beta", "gamma"]],
["blank-lines", "first\n\n\nlast line\n", ["first", "", "", "last line"]],
["empty", "", []],
["only-newline", "\n", [""]],
["no-final-newline", "one\ntwo\nthree", ["one", "two", "three"]],
["crlf", "one\r\ntwo\r\nthree\r\n", ["one", "two", "three"]],
["crlf-no-final-newline", "one\r\ntwo\r\nthree", ["one", "two", "three"]],
["mixed-endings", "one\r\ntwo\nthree\r\n", ["one", "two", "three"]],
["trailing-blank-line", "last\n\n", ["last", ""]],
["whitespace", " two spaces\ttab \n", [" two spaces\ttab "]],
["backslashes", "C:\\temp\\new\n", ["C:\\temp\\new"]],
[
"non-ascii",
"naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n",
["naïve café", "日本語のテキスト", "🙂🙂🙂🙂🙂🙂"],
],
["long-line", long + "\nend\n", [long, "end"]],
];
// The child process reads its real standard input and prints the result as JSON.
const modulePath = new URL("./readLines.js", import.meta.url).href;
const child = `const { readLines } = await import(${JSON.stringify(modulePath)});
process.stdout.write(JSON.stringify(await readLines()));`;
for (const [name, data, want] of cases) {
test(name, () => {
const result = spawnSync(process.execPath, ["--input-type=module", "-e", child], {
input: data,
encoding: "utf8",
maxBuffer: 4 << 20,
});
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(JSON.parse(result.stdout), want);
});
}
test("chunk-boundaries", async () => {
// One chunk ends between "\r" and "\n", and one ends inside the 2 bytes of "é".
const bytes = Buffer.from("one\r\ncafé\n");
const chunks = [bytes.subarray(0, 4), bytes.subarray(4, 9), bytes.subarray(9)];
const input = Readable.from(chunks, { objectMode: false });
assert.deepEqual(await readLines(input), ["one", "café"]);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
import { createInterface } from "node:readline";
import type { Readable } from "node:stream";
// Reads a stream to its end and returns its lines without "\n" or "\r\n".
// The default stream is standard input.
export async function readLines(input: Readable = process.stdin): Promise<string[]> {
// Decode the bytes as UTF-8, also when a character is split between two chunks.
input.setEncoding("utf8");
// crlfDelay: Infinity makes "\r\n" one line break even when a chunk ends between "\r" and "\n".
const reader = createInterface({ input, crlfDelay: Infinity });
const lines: string[] = [];
// The loop ends when the stream ends.
for await (const line of reader) {
lines.push(line);
}
return lines;
}
readLines.test.ts 56 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { Readable } from "node:stream";
import { test } from "node:test";
import { readLines } from "./readLines.ts";
const long = "x".repeat(1 << 20);
const cases: [string, string, string[]][] = [
["lf", "alpha\nbeta\ngamma\n", ["alpha", "beta", "gamma"]],
["blank-lines", "first\n\n\nlast line\n", ["first", "", "", "last line"]],
["empty", "", []],
["only-newline", "\n", [""]],
["no-final-newline", "one\ntwo\nthree", ["one", "two", "three"]],
["crlf", "one\r\ntwo\r\nthree\r\n", ["one", "two", "three"]],
["crlf-no-final-newline", "one\r\ntwo\r\nthree", ["one", "two", "three"]],
["mixed-endings", "one\r\ntwo\nthree\r\n", ["one", "two", "three"]],
["trailing-blank-line", "last\n\n", ["last", ""]],
["whitespace", " two spaces\ttab \n", [" two spaces\ttab "]],
["backslashes", "C:\\temp\\new\n", ["C:\\temp\\new"]],
[
"non-ascii",
"naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n",
["naïve café", "日本語のテキスト", "🙂🙂🙂🙂🙂🙂"],
],
["long-line", long + "\nend\n", [long, "end"]],
];
// The child process reads its real standard input and prints the result as JSON.
const modulePath = new URL("./readLines.ts", import.meta.url).href;
const child = `const { readLines } = await import(${JSON.stringify(modulePath)});
process.stdout.write(JSON.stringify(await readLines()));`;
for (const [name, data, want] of cases) {
test(name, () => {
const result = spawnSync(process.execPath, ["--input-type=module", "-e", child], {
input: data,
encoding: "utf8",
maxBuffer: 4 << 20,
});
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(JSON.parse(result.stdout), want);
});
}
test("chunk-boundaries", async () => {
// One chunk ends between "\r" and "\n", and one ends inside the 2 bytes of "é".
const bytes = Buffer.from("one\r\ncafé\n");
const chunks = [bytes.subarray(0, 4), bytes.subarray(4, 9), bytes.subarray(9)];
const input = Readable.from(chunks, { objectMode: false });
assert.deepEqual(await readLines(input), ["one", "café"]);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
// Package readlines reads the lines of standard input.
package readlines
import (
"bufio"
"io"
"os"
)
// MaxLine is the longest line, in bytes, that ReadLines accepts. The default limit of bufio.Scanner is 64 KiB.
const MaxLine = 64 << 20
// ReadLines reads r to its end and returns its lines, each without "\n" or "\r\n".
func ReadLines(r io.Reader) ([]string, error) {
lines := []string{}
s := bufio.NewScanner(r)
s.Buffer(make([]byte, 0, 64*1024), MaxLine)
// Scan returns false at the end of input or on an error.
for s.Scan() {
lines = append(lines, s.Text())
}
if err := s.Err(); err != nil {
return nil, err
}
return lines, nil
}
// ReadStdinLines reads standard input to its end and returns its lines.
func ReadStdinLines() ([]string, error) {
return ReadLines(os.Stdin)
}
read_lines_test.go 63 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
package readlines
import (
"os"
"path/filepath"
"slices"
"strings"
"testing"
)
// withStdin makes a file with the data the standard input of the process, and restores the old one at the end of the test.
func withStdin(t *testing.T, data string) {
t.Helper()
path := filepath.Join(t.TempDir(), "stdin.txt")
if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
t.Fatal(err)
}
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
saved := os.Stdin
os.Stdin = f
t.Cleanup(func() {
os.Stdin = saved
f.Close()
})
}
func TestCases(t *testing.T) {
long := strings.Repeat("x", 1<<20)
cases := []struct {
name string
data string
want []string
}{
{"lf", "alpha\nbeta\ngamma\n", []string{"alpha", "beta", "gamma"}},
{"blank-lines", "first\n\n\nlast line\n", []string{"first", "", "", "last line"}},
{"empty", "", []string{}},
{"only-newline", "\n", []string{""}},
{"no-final-newline", "one\ntwo\nthree", []string{"one", "two", "three"}},
{"crlf", "one\r\ntwo\r\nthree\r\n", []string{"one", "two", "three"}},
{"crlf-no-final-newline", "one\r\ntwo\r\nthree", []string{"one", "two", "three"}},
{"mixed-endings", "one\r\ntwo\nthree\r\n", []string{"one", "two", "three"}},
{"trailing-blank-line", "last\n\n", []string{"last", ""}},
{"whitespace", " two spaces\ttab \n", []string{" two spaces\ttab "}},
{"backslashes", `C:\temp\new` + "\n", []string{`C:\temp\new`}},
{"non-ascii", "naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n", []string{"naïve café", "日本語のテキスト", "🙂🙂🙂🙂🙂🙂"}},
{"long-line", long + "\nend\n", []string{long, "end"}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
withStdin(t, c.data)
got, err := ReadStdinLines()
if err != nil || !slices.Equal(got, c.want) {
t.Errorf("ReadStdinLines() = %q, %v; want %q, nil", got, err, c.want)
}
})
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
//! Read the lines of standard input.
use std::io::{self, BufRead};
/// Reads the reader to its end and returns its lines, each without "\n" or "\r\n".
///
/// A line that is not valid UTF-8 gives an error of kind `InvalidData`.
pub fn read_lines(reader: impl BufRead) -> io::Result<Vec<String>> {
reader.lines().collect()
}
/// Reads standard input to its end and returns its lines.
pub fn read_stdin_lines() -> io::Result<Vec<String>> {
// The lock gives a buffered reader that implements BufRead.
read_lines(io::stdin().lock())
}
tests/read_lines_test.rs 75 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-from-standard-input/.
use std::io::{Cursor, Write};
use std::process::{Command, Stdio};
use algo_read_from_standard_input::{read_lines, read_stdin_lines};
fn case(name: &'static str, data: &str, want: &[&str]) -> (&'static str, Vec<u8>, Vec<String>) {
(name, data.as_bytes().to_vec(), want.iter().map(|s| s.to_string()).collect())
}
fn cases() -> Vec<(&'static str, Vec<u8>, Vec<String>)> {
let long = "x".repeat(1 << 20);
vec![
case("lf", "alpha\nbeta\ngamma\n", &["alpha", "beta", "gamma"]),
case("blank-lines", "first\n\n\nlast line\n", &["first", "", "", "last line"]),
case("empty", "", &[]),
case("only-newline", "\n", &[""]),
case("no-final-newline", "one\ntwo\nthree", &["one", "two", "three"]),
case("crlf", "one\r\ntwo\r\nthree\r\n", &["one", "two", "three"]),
case("crlf-no-final-newline", "one\r\ntwo\r\nthree", &["one", "two", "three"]),
case("mixed-endings", "one\r\ntwo\nthree\r\n", &["one", "two", "three"]),
case("trailing-blank-line", "last\n\n", &["last", ""]),
case("whitespace", " two spaces\ttab \n", &[" two spaces\ttab "]),
case("backslashes", "C:\\temp\\new\n", &["C:\\temp\\new"]),
case(
"non-ascii",
"naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n",
&["naïve café", "日本語のテキスト", "🙂🙂🙂🙂🙂🙂"],
),
case("long-line", &format!("{long}\nend\n"), &[&long, "end"]),
]
}
#[test]
fn reader_cases() {
for (name, data, want) in cases() {
let got = read_lines(Cursor::new(data)).unwrap();
assert!(got == want, "case {name}");
}
}
/// The child mode of this test binary: it reads its real standard input and prints the lines.
#[test]
fn child_reads_stdin() {
if std::env::var_os("READ_LINES_CHILD").is_none() {
return;
}
let lines = read_stdin_lines().unwrap();
println!("lines={lines:?}");
}
/// Runs this test binary again, with each case on its standard input.
#[test]
fn stdin_cases() {
let exe = std::env::current_exe().unwrap();
for (name, data, want) in cases() {
let mut child = Command::new(&exe)
.args(["--exact", "child_reads_stdin", "--nocapture", "--test-threads=1"])
.env("READ_LINES_CHILD", "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
// A thread writes the input, so a full pipe cannot block the test.
let writer = std::thread::spawn(move || stdin.write_all(&data));
let out = child.wait_with_output().unwrap();
writer.join().unwrap().unwrap();
assert!(out.status.success(), "case {name}");
let stdout = String::from_utf8(out.stdout).unwrap();
assert!(stdout.contains(&format!("lines={want:?}\n")), "case {name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-from-standard-input/.
# Runs on Bash 3.2 and later.
# read_lines
# Reads standard input to its end and puts its lines in the global array "lines", each without its "\n" or "\r\n".
read_lines() {
lines=()
local line
# IFS= keeps leading and trailing blanks. -r keeps backslashes.
# read fails at the end of input. On a last line with no newline it fails too, but it still sets $line.
while IFS= read -r line || [[ -n $line ]]; do
if [[ $line == *$'\r' ]]; then
line=${line%?}
fi
lines+=("$line")
done
}
# Run as a script, it prints each line.
if [[ ${BASH_SOURCE[0]} == "$0" ]]; then
read_lines
if ((${#lines[@]} > 0)); then
printf '%s\n' "${lines[@]}"
fi
fi
test_read_lines.bats 41 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-from-standard-input/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/read_lines.sh"
file="$BATS_TEST_TMPDIR/input.txt"
}
check() { # check BYTES WANT...
printf '%b' "$1" >"$file"
shift
read_lines <"$file"
[ "${#lines[@]}" -eq "$#" ] || return 1
local i=0 want
for want in "$@"; do
[ "${lines[i]}" = "$want" ] || return 1
i=$((i + 1))
done
}
@test "lf" { check 'alpha\nbeta\ngamma\n' alpha beta gamma; }
@test "blank-lines" { check 'first\n\n\nlast line\n' first "" "" "last line"; }
@test "empty" { check ''; }
@test "only-newline" { check '\n' ""; }
@test "no-final-newline" { check 'one\ntwo\nthree' one two three; }
@test "crlf" { check 'one\r\ntwo\r\nthree\r\n' one two three; }
@test "crlf-no-final-newline" { check 'one\r\ntwo\r\nthree' one two three; }
@test "mixed-endings" { check 'one\r\ntwo\nthree\r\n' one two three; }
@test "trailing-blank-line" { check 'last\n\n' last ""; }
@test "whitespace" { check ' two spaces\ttab \n' $' two spaces\ttab '; }
@test "backslashes" { check 'C:\\temp\\new\n' 'C:\temp\new'; }
@test "non-ascii" { check 'naïve café\n日本語のテキスト\n🙂🙂🙂🙂🙂🙂\n' "naïve café" "日本語のテキスト" "🙂🙂🙂🙂🙂🙂"; }
@test "long-line" {
local long
long=$(head -c 1048576 /dev/zero | tr '\0' x)
check "$long\nend\n" "$long" end
}
References
- The Open Group, POSIX.1-2024, stderr, stdin, stdout, Description
- The Open Group, POSIX.1-2024, pread, read, Description
- The Open Group, POSIX.1-2024, getdelim, getline, Description, Return Value
- The Open Group, POSIX.1-2024, Base Definitions, Chapter 11, General Terminal Interface, 11.1.6 Canonical Mode Input Processing, 11.1.9 Special Characters (EOF)
- The Open Group, POSIX.1-2024, Base Definitions, Chapter 12, Utility Conventions, 12.2 Utility Syntax Guidelines, Guideline 13
- The Python Standard Library, sys, System-specific parameters and functions, sys.stdin
- The Python Standard Library, Built-in Functions, input
- The Python Standard Library, io, Core tools for working with streams, TextIOWrapper.reconfigure
- Node.js documentation, Process, process.stdin
- Node.js documentation, Readline, readline.createInterface(options), crlfDelay; Event 'close'; rl[Symbol.asyncIterator]()
- Node.js documentation, Stream, readable.setEncoding(encoding)
- Node.js documentation, Web Streams API, Utility Consumers, streamConsumers.text(stream)
- Java SE 25 API, java.lang.System, in, setIn(InputStream), getProperties() (stdin.encoding)
- Java SE 25 API, java.io.BufferedReader, readLine(), lines()
- Java SE 25 API, java.util.Scanner, nextLine(), nextInt()
- .NET API reference, Console.In, Remarks
- .NET API reference, Console.ReadLine, Returns, Remarks
- .NET API reference, TextReader.ReadLine, Returns, Remarks
- Go standard library, package bufio, Scanner, ScanLines, MaxScanTokenSize
- Go standard library, package io, ReadAll, EOF
- Go standard library, package fmt, Scanning, Scan
- The Rust Standard Library, std::io::Stdin, lock, read_line, impl Read for Stdin (read_to_string)
- The Rust Standard Library, std::io::BufRead, read_line, lines
- cppreference.com, std::getline
- GNU Bash Reference Manual, Bash Builtin Commands, 4.2, read
- GNU Bash Reference Manual, Command Substitution, 3.5.4
- GNU Bash Reference Manual, Pipelines, 3.2.3
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 |
|
The native tests pass in 9 of 10 languages in this build.
Tag YW44TZ Edit this page History Report an error Markdown