Taskintro
Read a whole file
Also called read a file into a string, read an entire file, slurp a file.
Read all of a UTF-8 file in one call and return its text with no change to line ends, a byte order mark or final newlines. Report an error for a missing file or bad bytes.
- Evidence
- Code in 10 languages
Task
Read all of a text file in one call, and return its text as one string.
The file is UTF-8. The solution returns the text with no change. A CRLF (\r\n) stays CRLF, a lone CR stays, a byte order mark stays as U+FEFF, and all final newlines stay. An empty file gives the empty string.
If the file does not exist, if the path names a directory, or if the bytes are not valid UTF-8, the solution reports an error and returns no text. It must not put U+FFFD in place of bad bytes and continue.
The whole file goes into memory, so use this only for a file that is small enough. For a large file, Read a file line by line keeps only one line in memory. To get the bytes with no decoding, see Read a binary file.
SQL, regular expressions, HTML and CSS do not apply, because none of them can open a file.
Solutions
Most languages have one call that reads all of a file. The differences are in what the call does to the text.
- Python.
open(path, encoding="utf-8", newline="").read(). Giveencoding, because before Python 3.15 the default encoding comes from the locale. Givenewline="", because the defaultnewline=Nonechanges\r\nand\rto\n. The codec"utf-8"keeps a byte order mark.pathlib.Path.read_bytesgives the bytes. - JavaScript and TypeScript (Node.js).
fsPromises.readFile(path)gives aBuffer. ATextDecoderwithfatal: trueandignoreBOM: truedecodes it. With no options,TextDecoderremoves a byte order mark and puts U+FFFD in place of bad bytes.readFile(path, "utf8")also puts U+FFFD in place of bad bytes. The TypeScript file adds types only. - Java.
Files.readString(path), from Java 11, decodes UTF-8. It throwsMalformedInputExceptionon bad bytes, and it keeps a byte order mark.Files.readAllBytes(path)gives the bytes. - C#.
File.ReadAllBytes(path), thennew UTF8Encoding(false, true).GetString(bytes). The second argumenttruemakes bad bytes throwDecoderFallbackException. Do not useFile.ReadAllText(path)here: it uses a byte order mark to find the encoding and removes it, and it puts U+FFFD in place of bad bytes. - Go.
os.ReadFile(path)gives a[]byte. It does not decode, so the code callsutf8.Validbefore it converts the bytes to astring. - Rust.
fs::read_to_string(path)returnsio::Result<String>. Bytes that are not valid UTF-8 give an error of kindInvalidData.fs::read(path)gives aVec<u8>. - C. ISO C has no call for a whole file. The code opens the file with
fopen(path, "rb"), usesfstatto refuse a directory and to guess the size, and callsfreaduntil it gives less than it was asked for. Thenferrortells an error from the end of the file. The code checks the UTF-8 itself, and returns a buffer with a 0 byte after the text. - C++. A binary
std::ifstreamand twostd::istreambuf_iterator<char>put all the bytes into astd::string. The code checks for a directory first, checks the UTF-8 itself, and returnsstd::expected(C++23). - Bash.
text=$(iconv -f UTF-8 -t UTF-8 -- "$path" && printf x), thentext=${text%x}.iconvstops with an error on bad bytes, and thexkeeps the final newlines. A Bash variable cannot hold a 0 byte.
PowerShell Get-Content -Raw returns all of a file as one string. Without -Raw, it returns an array of lines.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl, with one file for each in fixtures/. The cases that must give an error are in cases/errors.jsonl. The native tests also read a file of 1 MiB.
empty: no bytes. The result is the empty string, not an error.no-final-newline: the text ends with no\n. Nothing is added.trailing-newlines:end\n\n\n. Bash$(...)removes all three newlines.crlfandmixed-endings:\r\nand a lone\rstay. Python with the defaultnewlinechanges them to\n.bom: the bytesEF BB BFat the start become U+FEFF. C#File.ReadAllTextand a defaultTextDecoderremove it.whitespace: leading and trailing blanks and a tab stay.non-ascii: characters of 2, 3 and 4 bytes.- Errors: a missing file, a directory, the bytes
FF FE, a sequence cut by the end of the file, an encoded surrogate (ED A0 80) and an overlong form (C0 AF). RFC 3629 does not allow these bytes.
Pitfalls
- Line ends that change in Python. With the default
newline=None, Python changes\r\nto\nwhen it reads text:
This code runs but gives a wrong answer on purpose.
import os
import tempfile
path = os.path.join(tempfile.mkdtemp(), "crlf.txt")
with open(path, "wb") as f:
f.write(b"one\r\ntwo\r\n")
with open(path, encoding="utf-8") as f:
print(repr(f.read()))
'one\ntwo\n'
Give newline="" to get the text as it is in the file:
import os
import tempfile
path = os.path.join(tempfile.mkdtemp(), "crlf.txt")
with open(path, "wb") as f:
f.write(b"one\r\ntwo\r\n")
with open(path, encoding="utf-8", newline="") as f:
print(repr(f.read()))
'one\r\ntwo\r\n'
- Final newlines that Bash removes. Command substitution removes all newlines at the end of the output, and
$(<file)is a command substitution:
This code runs but gives a wrong answer on purpose.
file=$(mktemp)
printf 'end\n\n\n' >"$file"
text=$(<"$file")
printf '%d characters: %q\n' "${#text}" "$text"
rm -f -- "$file"
3 characters: end
Print one more character after the file, and then remove it:
file=$(mktemp)
printf 'end\n\n\n' >"$file"
text=$(cat -- "$file" && printf x)
text=${text%x}
printf '%d characters: %q\n' "${#text}" "$text"
rm -f -- "$file"
6 characters: $'end\n\n\n'
- Silent replacement of bad bytes. Node.js
readFile(path, "utf8"), C#File.ReadAllTextand a defaultTextDecoderput U+FFFD in place of bad bytes and give no error. Goos.ReadFiledoes not check the bytes at all. Later code then works on text that is not the text of the file:
This code runs but gives a wrong answer on purpose.
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const path = join(mkdtempSync(join(tmpdir(), "bad-")), "bad.txt");
writeFileSync(path, Uint8Array.from([0x6f, 0x6b, 0x0a, 0xff, 0xfe, 0x0a]));
const text = readFileSync(path, "utf8");
console.log(JSON.stringify(text));
"ok\n��\n"
A TextDecoder with fatal: true throws a TypeError:
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const path = join(mkdtempSync(join(tmpdir(), "bad-")), "bad.txt");
writeFileSync(path, Uint8Array.from([0x6f, 0x6b, 0x0a, 0xff, 0xfe, 0x0a]));
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
try {
decoder.decode(readFileSync(path));
} catch (err) {
console.log(err.name + ": " + err.code);
}
TypeError: ERR_ENCODING_INVALID_ENCODED_DATA
- A byte order mark that C# removes.
File.ReadAllText(path)uses a byte order mark to find the encoding, and the mark is not in the result. Here it also changes the bad byteFFto U+FFFD:
This code runs but gives a wrong answer on purpose.
using System;
using System.IO;
string path = Path.Combine(Directory.CreateTempSubdirectory().FullName, "bom.txt");
File.WriteAllBytes(path, [0xEF, 0xBB, 0xBF, (byte)'h', (byte)'i', 0xFF]);
string text = File.ReadAllText(path);
foreach (char c in text) Console.Write($"U+{(int)c:X4} ");
Console.WriteLine();
U+0068 U+0069 U+FFFD
A strict UTF8Encoding keeps the mark. With the byte FF, it would throw:
using System;
using System.IO;
using System.Text;
string path = Path.Combine(Directory.CreateTempSubdirectory().FullName, "bom.txt");
File.WriteAllBytes(path, [0xEF, 0xBB, 0xBF, (byte)'h', (byte)'i', (byte)'\n']);
var strict = new UTF8Encoding(false, true);
string text = strict.GetString(File.ReadAllBytes(path));
foreach (char c in text) Console.Write($"U+{(int)c:X4} ");
Console.WriteLine();
U+FEFF U+0068 U+0069 U+000A
- Files that are too large. The whole file must fit in memory, and some languages have a lower limit. Java
Files.readStringandFiles.readAllBytesthrowOutOfMemoryErrorif the file is "extremely large, for example larger than 2GB". In Node.js, a string can have at mostbuffer.constants.MAX_STRING_LENGTHUTF-16 code units. Read a large file line by line or in blocks. - A size from
statthat is wrong. Code that callsfstat, allocatesst_sizebytes and callsfreadonce can lose data. The file can grow before the read, and POSIX does not say whatst_sizemeans for most types of file other than a regular file.freadcan also give fewer bytes than it was asked for. Read in a loop untilfreadgives less, and then callferror. - A directory. POSIX
fopengives the errorEISDIRfor a directory only when the mode "requires write access". Sofopen(path, "rb")on a directory can succeed. The C and C++ solutions check the type of the file before they read.
Related tasks
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-a-whole-file/.
import os
def read_text(path: str | os.PathLike[str]) -> str:
"""Return all of the text of a UTF-8 file, with no change to it."""
# newline="" keeps "\r\n" as it is; the default would give "\n".
# The codec "utf-8" keeps a byte order mark as U+FEFF.
with open(path, encoding="utf-8", newline="") as file:
return file.read()
test_read_text.py 54 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-whole-file/.
from pathlib import Path
import pytest
from read_text import read_text
CASES = {
"lf": "alpha\nbeta\n",
"paragraphs": "first line\n\nsecond paragraph\n",
"non-ascii": "naïve café\n日本語\n🙂\n",
"empty": "",
"no-final-newline": "one\ntwo",
"trailing-newlines": "end\n\n\n",
"crlf": "one\r\ntwo\r\n",
"mixed-endings": "lf\ncrlf\r\ncr\rend",
"bom": "\ufeffhead\n",
"whitespace": " two spaces\ttab \n",
"large": "0123456789abcdef" * 65536,
}
INVALID_UTF8 = {
"invalid-byte": b"ok\n\xff\xfe\n",
"truncated-at-end": b"ok\ncaf\xc3",
"encoded-surrogate": b"a\xed\xa0\x80b\n",
"overlong": b"\xc0\xaf\n",
}
@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
path = tmp_path / "input.txt"
path.write_bytes(CASES[name].encode())
assert read_text(path) == CASES[name]
def test_missing_file(tmp_path: Path) -> None:
with pytest.raises(FileNotFoundError):
read_text(tmp_path / "missing.txt")
def test_directory(tmp_path: Path) -> None:
with pytest.raises(OSError):
read_text(tmp_path)
@pytest.mark.parametrize("name", INVALID_UTF8)
def test_invalid_utf8(tmp_path: Path, name: str) -> None:
path = tmp_path / "input.txt"
path.write_bytes(INVALID_UTF8[name])
with pytest.raises(UnicodeDecodeError):
read_text(path)
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
// since: C++23 (std::expected)
#include "read_text.hpp"
#include <fstream>
#include <iterator>
#include <string_view>
#include <system_error>
namespace {
// Checks that s is valid UTF-8 (RFC 3629): no overlong form, no surrogate,
// nothing above U+10FFFF.
bool utf8_valid(std::string_view s) {
for (std::size_t i = 0; i < s.size();) {
auto c = static_cast<unsigned char>(s[i]);
std::size_t len = 0;
unsigned char lo = 0x80, hi = 0xBF; // the range of the second byte
if (c < 0x80) {
++i;
continue;
} else if (c >= 0xC2 && c <= 0xDF) {
len = 2;
} else if (c >= 0xE0 && c <= 0xEF) {
len = 3;
if (c == 0xE0) lo = 0xA0; // no overlong form
if (c == 0xED) hi = 0x9F; // no surrogate
} else if (c >= 0xF0 && c <= 0xF4) {
len = 4;
if (c == 0xF0) lo = 0x90; // no overlong form
if (c == 0xF4) hi = 0x8F; // no value above U+10FFFF
} else {
return false;
}
if (s.size() - i < len) return false;
auto second = static_cast<unsigned char>(s[i + 1]);
if (second < lo || second > hi) return false;
for (std::size_t j = 2; j < len; ++j) {
if ((static_cast<unsigned char>(s[i + j]) & 0xC0) != 0x80) return false;
}
i += len;
}
return true;
}
} // namespace
std::expected<std::string, ReadError> read_text(const std::filesystem::path& path) {
std::error_code ec;
auto status = std::filesystem::status(path, ec);
if (status.type() == std::filesystem::file_type::not_found) {
return std::unexpected(ReadError::not_found);
}
// An ifstream opens a directory with no error on Linux, so check first.
if (std::filesystem::is_directory(status)) return std::unexpected(ReadError::not_a_file);
std::ifstream in(path, std::ios::binary); // binary: no change to CR LF
if (!in) return std::unexpected(ReadError::cannot_open);
std::string text{std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
if (in.bad()) return std::unexpected(ReadError::read_failed);
if (!utf8_valid(text)) return std::unexpected(ReadError::invalid_utf8);
return text;
}
read_text.hpp 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
// since: C++23 (std::expected)
#pragma once
#include <expected>
#include <filesystem>
#include <string>
enum class ReadError { not_found, not_a_file, cannot_open, read_failed, invalid_utf8 };
// Reads all of the UTF-8 text file at path. The bytes come back as they are
// in the file, in a std::string, after a check that they are valid UTF-8.
std::expected<std::string, ReadError> read_text(const std::filesystem::path& path);
test_read_text.cpp 77 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "read_text.hpp"
namespace {
const std::filesystem::path input = "read_text_input.txt";
void write_file(std::string_view data) {
std::ofstream out(input, std::ios::binary);
out << data;
}
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() {
using namespace std::string_literals;
std::string large;
for (int i = 0; i < 65536; ++i) large += "0123456789abcdef";
const std::vector<std::pair<std::string, std::string>> cases = {
{"lf", "alpha\nbeta\n"},
{"paragraphs", "first line\n\nsecond paragraph\n"},
{"non-ascii", "naïve café\n日本語\n🙂\n"},
{"empty", ""},
{"no-final-newline", "one\ntwo"},
{"trailing-newlines", "end\n\n\n"},
{"crlf", "one\r\ntwo\r\n"},
{"mixed-endings", "lf\ncrlf\r\ncr\rend"},
{"bom", "\xEF\xBB\xBFhead\n"},
{"whitespace", " two spaces\ttab \n"},
{"large", large},
};
for (const auto& [name, data] : cases) {
write_file(data);
auto got = read_text(input);
check(name, got.has_value() && *got == data);
}
std::filesystem::remove(input);
check("missing", read_text("no_such_file.txt").error_or(ReadError::read_failed) ==
ReadError::not_found);
check("directory", read_text(".").error_or(ReadError::read_failed) == ReadError::not_a_file);
const std::vector<std::pair<std::string, std::string>> invalid = {
{"invalid-byte", "ok\n\xFF\xFE\n"},
{"truncated-at-end", "ok\ncaf\xC3"},
{"encoded-surrogate", "a\xED\xA0\x80"s + "b\n"},
{"overlong", "\xC0\xAF\n"},
};
for (const auto& [name, data] : invalid) {
write_file(data);
check(name, read_text(input).error_or(ReadError::read_failed) == ReadError::invalid_utf8);
}
std::filesystem::remove(input);
if (failures != 0) return EXIT_FAILURE;
std::puts("all tests passed");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
/** Reads all of a UTF-8 text file in one call. */
public final class ReadText {
private ReadText() {}
/**
* Returns all of the text of a UTF-8 file, with no change to it. Files.readString decodes UTF-8,
* keeps CR LF and a byte order mark, and throws MalformedInputException on bad bytes.
*/
public static String readText(Path path) throws IOException {
return Files.readString(path);
}
}
ReadTextTest.java 72 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-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.MalformedInputException;
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 ReadTextTest {
@TempDir Path dir;
private Path write(byte[] data) throws IOException {
return Files.write(dir.resolve("input.txt"), data);
}
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("lf", "alpha\nbeta\n"),
Arguments.of("paragraphs", "first line\n\nsecond paragraph\n"),
Arguments.of("non-ascii", "naïve café\n日本語\n🙂\n"),
Arguments.of("empty", ""),
Arguments.of("no-final-newline", "one\ntwo"),
Arguments.of("trailing-newlines", "end\n\n\n"),
Arguments.of("crlf", "one\r\ntwo\r\n"),
Arguments.of("mixed-endings", "lf\ncrlf\r\ncr\rend"),
Arguments.of("bom", "\uFEFFhead\n"),
Arguments.of("whitespace", " two spaces\ttab \n"),
Arguments.of("large", "0123456789abcdef".repeat(65536)));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void readsText(String name, String text) throws IOException {
assertEquals(text, ReadText.readText(write(text.getBytes(StandardCharsets.UTF_8))));
}
@Test
void missingFile() {
assertThrows(NoSuchFileException.class, () -> ReadText.readText(dir.resolve("missing.txt")));
}
@Test
void directory() {
assertThrows(IOException.class, () -> ReadText.readText(dir));
}
static Stream<Arguments> invalidUtf8() {
return Stream.of(
Arguments.of("invalid-byte", new byte[] {'o', 'k', '\n', (byte) 0xff, (byte) 0xfe, '\n'}),
Arguments.of("truncated-at-end", new byte[] {'o', 'k', '\n', 'c', 'a', 'f', (byte) 0xc3}),
Arguments.of(
"encoded-surrogate", new byte[] {'a', (byte) 0xed, (byte) 0xa0, (byte) 0x80, 'b', '\n'}),
Arguments.of("overlong", new byte[] {(byte) 0xc0, (byte) 0xaf, '\n'}));
}
@ParameterizedTest(name = "{0}")
@MethodSource("invalidUtf8")
void rejectsInvalidUtf8(String name, byte[] data) {
assertThrows(MalformedInputException.class, () -> ReadText.readText(write(data)));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
// fileno and fstat are in POSIX.1-2008, not in ISO C.
#define _POSIX_C_SOURCE 200809L
#include "read_text.h"
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
// utf8_valid checks that s[0..n) is valid UTF-8 (RFC 3629). It rejects
// overlong forms, surrogates and values above U+10FFFF.
static bool utf8_valid(const unsigned char *s, size_t n) {
for (size_t i = 0; i < n;) {
unsigned char c = s[i];
size_t len;
unsigned char lo = 0x80, hi = 0xBF; // the range of the second byte
if (c < 0x80) {
i++;
continue;
} else if (c >= 0xC2 && c <= 0xDF) {
len = 2;
} else if (c >= 0xE0 && c <= 0xEF) {
len = 3;
if (c == 0xE0) lo = 0xA0; // no overlong form
if (c == 0xED) hi = 0x9F; // no surrogate
} else if (c >= 0xF0 && c <= 0xF4) {
len = 4;
if (c == 0xF0) lo = 0x90; // no overlong form
if (c == 0xF4) hi = 0x8F; // no value above U+10FFFF
} else {
return false;
}
if (n - i < len || s[i + 1] < lo || s[i + 1] > hi) return false;
for (size_t j = 2; j < len; j++) {
if ((s[i + j] & 0xC0) != 0x80) return false;
}
i += len;
}
return true;
}
char *read_text(const char *path, size_t *len) {
FILE *f = fopen(path, "rb");
if (f == NULL) return NULL;
int err = 0;
char *buf = NULL;
size_t n = 0;
struct stat st;
if (fstat(fileno(f), &st) != 0) {
err = errno;
} else if (S_ISDIR(st.st_mode)) {
err = EISDIR;
} else {
// The size from fstat is only a first guess: the file can change
// while it is read, and POSIX does not say what st_size means for
// most types of file other than a regular file. So read until fread
// gives less than it was asked for.
size_t cap = st.st_size > 0 ? (size_t)st.st_size + 1 : 4096;
buf = malloc(cap);
while (buf != NULL) {
n += fread(buf + n, 1, cap - n, f);
if (n < cap) break; // the end of the file, or an error
char *bigger = realloc(buf, cap * 2);
if (bigger == NULL) {
free(buf);
buf = NULL;
break;
}
buf = bigger;
cap *= 2;
}
if (buf == NULL) {
err = ENOMEM;
} else if (ferror(f)) {
err = errno != 0 ? errno : EIO;
} else if (!utf8_valid((const unsigned char *)buf, n)) {
err = EILSEQ;
} else {
buf[n] = '\0'; // n < cap, so there is room
}
}
fclose(f);
if (err != 0) {
free(buf);
errno = err;
return NULL;
}
*len = n;
return buf;
}
read_text.h 17 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
#ifndef READ_TEXT_H
#define READ_TEXT_H
#include <stddef.h>
// read_text reads all of the UTF-8 text file at path. It returns a new
// buffer that the caller must free, with a 0 byte after the text, and stores
// the number of bytes of the text in *len. The text can hold 0 bytes, so use
// *len and not strlen. On an error it returns NULL and sets errno: EISDIR for
// a directory, EILSEQ for bytes that are not valid UTF-8, or the error of
// fopen, fstat or fread.
char *read_text(const char *path, size_t *len);
#endif
test_read_text.c 81 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
#include "read_text.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char *path = "read_text_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) {
write_file(data, n);
size_t len = 99;
char *text = read_text(path, &len);
if (text == NULL || len != n || memcmp(text, data, n) != 0 || text[n] != '\0') {
fprintf(stderr, "case %s: wrong text\n", name);
exit(1);
}
free(text);
}
static void check_error(const char *name, const char *file, int want) {
size_t len;
errno = 0;
char *text = read_text(file, &len);
if (text != NULL || errno != want) {
fprintf(stderr, "case %s: want errno %d, got %d\n", name, want, errno);
exit(1);
}
}
static void check_invalid(const char *name, const char *data, size_t n) {
write_file(data, n);
check_error(name, path, EILSEQ);
}
#define CASE(name, data) check(name, data, sizeof(data) - 1)
#define INVALID(name, data) check_invalid(name, data, sizeof(data) - 1)
int main(void) {
CASE("lf", "alpha\nbeta\n");
CASE("paragraphs", "first line\n\nsecond paragraph\n");
CASE("non-ascii", "na\xc3\xafve caf\xc3\xa9\n\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\n\xf0\x9f\x99\x82\n");
CASE("empty", "");
CASE("no-final-newline", "one\ntwo");
CASE("trailing-newlines", "end\n\n\n");
CASE("crlf", "one\r\ntwo\r\n");
CASE("mixed-endings", "lf\ncrlf\r\ncr\rend");
CASE("bom", "\xef\xbb\xbfhead\n");
CASE("whitespace", " two spaces\ttab \n");
size_t big = 16 * 65536;
char *large = malloc(big);
assert(large != NULL);
for (size_t i = 0; i < big; i++) large[i] = "0123456789abcdef"[i % 16];
check("large", large, big);
free(large);
remove(path);
check_error("missing", "no_such_file.txt", ENOENT);
check_error("directory", ".", EISDIR);
INVALID("invalid-byte", "ok\n\xff\xfe\n");
INVALID("truncated-at-end", "ok\ncaf\xc3");
INVALID("encoded-surrogate", "a\xed\xa0\x80" "b\n");
INVALID("overlong", "\xc0\xaf\n");
remove(path);
puts("all tests passed");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
using System.Text;
public static class ReadText
{
// false: no byte order mark is written; true: bad bytes throw.
private static readonly UTF8Encoding Strict = new(false, true);
/// <summary>Returns all of the text of a UTF-8 file, with no change to it.</summary>
/// <remarks>File.ReadAllText would drop a byte order mark and put U+FFFD for bad bytes.</remarks>
public static string Read(string path) => Strict.GetString(File.ReadAllBytes(path));
}
ReadTextTests.cs 66 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
using System.Text;
using Xunit;
public sealed class ReadTextTests : IDisposable
{
private readonly string dir = Directory.CreateTempSubdirectory("read-text-").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> Cases => new()
{
{ "lf", "alpha\nbeta\n" },
{ "paragraphs", "first line\n\nsecond paragraph\n" },
{ "non-ascii", "naïve café\n日本語\n🙂\n" },
{ "empty", "" },
{ "no-final-newline", "one\ntwo" },
{ "trailing-newlines", "end\n\n\n" },
{ "crlf", "one\r\ntwo\r\n" },
{ "mixed-endings", "lf\ncrlf\r\ncr\rend" },
{ "bom", "\uFEFFhead\n" },
{ "whitespace", " two spaces\ttab \n" },
{ "large", string.Concat(Enumerable.Repeat("0123456789abcdef", 65536)) },
};
[Theory]
[MemberData(nameof(Cases))]
public void ReadsText(string name, string text)
{
Assert.Equal(text, ReadText.Read(Write(Encoding.UTF8.GetBytes(text))));
Assert.False(string.IsNullOrEmpty(name));
}
[Fact]
public void MissingFile() =>
Assert.Throws<FileNotFoundException>(() => ReadText.Read(Path.Combine(dir, "missing.txt")));
[Fact]
public void PathIsADirectory() =>
Assert.ThrowsAny<Exception>(() => ReadText.Read(dir));
public static TheoryData<string, byte[]> InvalidUtf8 => new()
{
{ "invalid-byte", [0x6f, 0x6b, 0x0a, 0xff, 0xfe, 0x0a] },
{ "truncated-at-end", [0x6f, 0x6b, 0x0a, 0x63, 0x61, 0x66, 0xc3] },
{ "encoded-surrogate", [0x61, 0xed, 0xa0, 0x80, 0x62, 0x0a] },
{ "overlong", [0xc0, 0xaf, 0x0a] },
};
[Theory]
[MemberData(nameof(InvalidUtf8))]
public void RejectsInvalidUtf8(string name, byte[] data)
{
Assert.Throws<DecoderFallbackException>(() => ReadText.Read(Write(data)));
Assert.False(string.IsNullOrEmpty(name));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
import { readFile } from "node:fs/promises";
// fatal: true rejects bad bytes; the default puts U+FFFD in their place.
// ignoreBOM: true keeps a byte order mark as U+FEFF; the default drops it.
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
/** Return all of the text of a UTF-8 file, with no change to it. */
export async function readText(path) {
const bytes = await readFile(path);
return decoder.decode(bytes);
}
readText.test.js 67 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { readText } from "./readText.js";
const cases = {
lf: "alpha\nbeta\n",
paragraphs: "first line\n\nsecond paragraph\n",
"non-ascii": "naïve café\n日本語\n🙂\n",
empty: "",
"no-final-newline": "one\ntwo",
"trailing-newlines": "end\n\n\n",
crlf: "one\r\ntwo\r\n",
"mixed-endings": "lf\ncrlf\r\ncr\rend",
bom: "\uFEFFhead\n",
whitespace: " two spaces\ttab \n",
large: "0123456789abcdef".repeat(65536),
};
const invalidUtf8 = {
"invalid-byte": [0x6f, 0x6b, 0x0a, 0xff, 0xfe, 0x0a],
"truncated-at-end": [0x6f, 0x6b, 0x0a, 0x63, 0x61, 0x66, 0xc3],
"encoded-surrogate": [0x61, 0xed, 0xa0, 0x80, 0x62, 0x0a],
overlong: [0xc0, 0xaf, 0x0a],
};
async function withDir(body) {
const dir = await mkdtemp(join(tmpdir(), "read-text-"));
try {
await body(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
for (const [name, text] of Object.entries(cases)) {
test(name, () =>
withDir(async (dir) => {
const path = join(dir, "input.txt");
await writeFile(path, text, "utf8");
assert.equal(await readText(path), text);
}));
}
test("missing file", () =>
withDir(async (dir) => {
await assert.rejects(readText(join(dir, "missing.txt")), { code: "ENOENT" });
}));
test("directory", () =>
withDir(async (dir) => {
await assert.rejects(readText(dir), { code: "EISDIR" });
}));
for (const [name, bytes] of Object.entries(invalidUtf8)) {
test(name, () =>
withDir(async (dir) => {
const path = join(dir, "input.txt");
await writeFile(path, Uint8Array.from(bytes));
await assert.rejects(readText(path), TypeError);
}));
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
import { readFile } from "node:fs/promises";
// fatal: true rejects bad bytes; the default puts U+FFFD in their place.
// ignoreBOM: true keeps a byte order mark as U+FEFF; the default drops it.
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
/** Return all of the text of a UTF-8 file, with no change to it. */
export async function readText(path: string): Promise<string> {
const bytes = await readFile(path);
return decoder.decode(bytes);
}
readText.test.ts 67 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { readText } from "./readText.ts";
const cases: Record<string, string> = {
lf: "alpha\nbeta\n",
paragraphs: "first line\n\nsecond paragraph\n",
"non-ascii": "naïve café\n日本語\n🙂\n",
empty: "",
"no-final-newline": "one\ntwo",
"trailing-newlines": "end\n\n\n",
crlf: "one\r\ntwo\r\n",
"mixed-endings": "lf\ncrlf\r\ncr\rend",
bom: "\uFEFFhead\n",
whitespace: " two spaces\ttab \n",
large: "0123456789abcdef".repeat(65536),
};
const invalidUtf8: Record<string, number[]> = {
"invalid-byte": [0x6f, 0x6b, 0x0a, 0xff, 0xfe, 0x0a],
"truncated-at-end": [0x6f, 0x6b, 0x0a, 0x63, 0x61, 0x66, 0xc3],
"encoded-surrogate": [0x61, 0xed, 0xa0, 0x80, 0x62, 0x0a],
overlong: [0xc0, 0xaf, 0x0a],
};
async function withDir(body: (dir: string) => Promise<void>): Promise<void> {
const dir = await mkdtemp(join(tmpdir(), "read-text-"));
try {
await body(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
for (const [name, text] of Object.entries(cases)) {
test(name, () =>
withDir(async (dir) => {
const path = join(dir, "input.txt");
await writeFile(path, text, "utf8");
assert.equal(await readText(path), text);
}));
}
test("missing file", () =>
withDir(async (dir) => {
await assert.rejects(readText(join(dir, "missing.txt")), { code: "ENOENT" });
}));
test("directory", () =>
withDir(async (dir) => {
await assert.rejects(readText(dir), { code: "EISDIR" });
}));
for (const [name, bytes] of Object.entries(invalidUtf8)) {
test(name, () =>
withDir(async (dir) => {
const path = join(dir, "input.txt");
await writeFile(path, Uint8Array.from(bytes));
await assert.rejects(readText(path), TypeError);
}));
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
// Package readtext reads all of a UTF-8 text file in one call.
package readtext
import (
"errors"
"fmt"
"os"
"unicode/utf8"
)
// ErrInvalidUTF8 reports that the bytes of the file are not valid UTF-8.
var ErrInvalidUTF8 = errors.New("invalid UTF-8")
// ReadText returns all of the text of a UTF-8 file, with no change to it.
// os.ReadFile does not check the bytes, so ReadText checks them.
func ReadText(path string) (string, error) {
data, err := os.ReadFile(path)
if err != nil {
return "", err
}
if !utf8.Valid(data) {
return "", fmt.Errorf("%s: %w", path, ErrInvalidUTF8)
}
return string(data), nil
}
read_text_test.go 78 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
package readtext
import (
"errors"
"io/fs"
"os"
"path/filepath"
"strings"
"testing"
)
var cases = map[string]string{
"lf": "alpha\nbeta\n",
"paragraphs": "first line\n\nsecond paragraph\n",
"non-ascii": "naïve café\n日本語\n🙂\n",
"empty": "",
"no-final-newline": "one\ntwo",
"trailing-newlines": "end\n\n\n",
"crlf": "one\r\ntwo\r\n",
"mixed-endings": "lf\ncrlf\r\ncr\rend",
"bom": "\uFEFFhead\n",
"whitespace": " two spaces\ttab \n",
"large": strings.Repeat("0123456789abcdef", 65536),
}
var invalidUTF8 = map[string][]byte{
"invalid-byte": []byte("ok\n\xff\xfe\n"),
"truncated-at-end": []byte("ok\ncaf\xc3"),
"encoded-surrogate": []byte("a\xed\xa0\x80b\n"),
"overlong": []byte("\xc0\xaf\n"),
}
func write(t *testing.T, data []byte) string {
t.Helper()
path := filepath.Join(t.TempDir(), "input.txt")
if err := os.WriteFile(path, data, 0o644); err != nil {
t.Fatal(err)
}
return path
}
func TestCases(t *testing.T) {
for name, want := range cases {
t.Run(name, func(t *testing.T) {
got, err := ReadText(write(t, []byte(want)))
if err != nil || got != want {
t.Fatalf("ReadText = %q, %v; want %q", got, err, want)
}
})
}
}
func TestMissingFile(t *testing.T) {
_, err := ReadText(filepath.Join(t.TempDir(), "missing.txt"))
if !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("err = %v; want fs.ErrNotExist", err)
}
}
func TestDirectory(t *testing.T) {
if _, err := ReadText(t.TempDir()); err == nil {
t.Fatal("err = nil; want an error for a directory")
}
}
func TestInvalidUTF8(t *testing.T) {
for name, data := range invalidUTF8 {
t.Run(name, func(t *testing.T) {
_, err := ReadText(write(t, data))
if !errors.Is(err, ErrInvalidUTF8) {
t.Fatalf("err = %v; want ErrInvalidUTF8", err)
}
})
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
use std::fs;
use std::io;
use std::path::Path;
/// Returns all of the text of a UTF-8 file, with no change to it.
///
/// `fs::read_to_string` gives an error of kind `InvalidData` when the
/// bytes are not valid UTF-8. It keeps CR LF and a byte order mark.
pub fn read_text(path: impl AsRef<Path>) -> io::Result<String> {
fs::read_to_string(path)
}
tests/read_text_test.rs 69 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-whole-file/.
use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;
use algo_read_a_whole_file::read_text;
/// Returns a new empty directory for one test.
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("read-text-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
/// Writes the bytes to a new file and returns its path.
fn write(name: &str, data: &[u8]) -> PathBuf {
let path = temp_dir(name).join("input.txt");
fs::write(&path, data).unwrap();
path
}
#[test]
fn cases() {
let large = "0123456789abcdef".repeat(65536);
let cases = [
("lf", "alpha\nbeta\n"),
("paragraphs", "first line\n\nsecond paragraph\n"),
("non-ascii", "naïve café\n日本語\n🙂\n"),
("empty", ""),
("no-final-newline", "one\ntwo"),
("trailing-newlines", "end\n\n\n"),
("crlf", "one\r\ntwo\r\n"),
("mixed-endings", "lf\ncrlf\r\ncr\rend"),
("bom", "\u{FEFF}head\n"),
("whitespace", " two spaces\ttab \n"),
("large", large.as_str()),
];
for (name, text) in cases {
assert_eq!(read_text(write(name, text.as_bytes())).unwrap(), text, "{name}");
}
}
#[test]
fn missing_file() {
let err = read_text(temp_dir("missing").join("missing.txt")).unwrap_err();
assert_eq!(err.kind(), ErrorKind::NotFound);
}
#[test]
fn directory() {
assert!(read_text(temp_dir("directory")).is_err());
}
#[test]
fn invalid_utf8() {
let cases: [(&str, &[u8]); 4] = [
("invalid-byte", b"ok\n\xff\xfe\n"),
("truncated-at-end", b"ok\ncaf\xc3"),
("encoded-surrogate", b"a\xed\xa0\x80b\n"),
("overlong", b"\xc0\xaf\n"),
];
for (name, data) in cases {
let err = read_text(write(name, data)).unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidData, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-whole-file/.
# read_text NAME PATH
# Stores all of the text of the UTF-8 file PATH in the variable NAME, with no change.
# Returns a nonzero status, and does not set NAME, if PATH is missing, a directory
# or not valid UTF-8. A Bash variable cannot hold a 0 byte, so the text must have none.
read_text() {
local _read_text
if [[ -d $2 ]]; then
printf 'read_text: %s: is a directory\n' "$2" >&2
return 1
fi
# iconv stops with an error on a bad byte sequence or a missing file.
# $(...) drops all final newlines, so add an x after the text, then remove it.
_read_text=$(iconv -f UTF-8 -t UTF-8 -- "$2" && printf x) || return
printf -v "$1" '%s' "${_read_text%x}"
}
test_read_text.bats 51 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-whole-file/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/read_text.sh"
file="$BATS_TEST_TMPDIR/input.txt"
}
# "run" drops final newlines from $output, so these tests call read_text directly.
check() { # check BYTES
local want text
printf '%b' "$1" >"$file"
want=$(printf '%b' "$1" && printf x)
read_text text "$file"
[ "$text" = "${want%x}" ]
}
@test "lf" { check 'alpha\nbeta\n'; }
@test "paragraphs" { check 'first line\n\nsecond paragraph\n'; }
@test "non-ascii" { check 'naïve café\n日本語\n🙂\n'; }
@test "empty" { check ''; }
@test "no-final-newline" { check 'one\ntwo'; }
@test "trailing-newlines" { check 'end\n\n\n'; }
@test "crlf" { check 'one\r\ntwo\r\n'; }
@test "mixed-endings" { check 'lf\ncrlf\r\ncr\rend'; }
@test "bom" { check '\xef\xbb\xbfhead\n'; }
@test "whitespace" { check ' two spaces\ttab \n'; }
@test "large" {
local text want
want=$(printf '0123456789abcdef%.0s' {1..65536})
printf '%s' "$want" >"$file"
read_text text "$file"
[ "$text" = "$want" ]
}
@test "missing" {
run ! read_text text "$BATS_TEST_TMPDIR/missing.txt"
}
@test "directory" {
run ! read_text text "$BATS_TEST_TMPDIR"
}
@test "invalid-byte" { printf 'ok\n\xff\xfe\n' >"$file"; run ! read_text text "$file"; }
@test "truncated-at-end" { printf 'ok\ncaf\xc3' >"$file"; run ! read_text text "$file"; }
@test "encoded-surrogate" { printf 'a\xed\xa0\x80b\n' >"$file"; run ! read_text text "$file"; }
@test "overlong" { printf '\xc0\xaf\n' >"$file"; run ! read_text text "$file"; }
References
- The Python Standard Library, io, Core tools for working with streams, class io.TextIOWrapper, the newline parameter
- PEP 686, Make UTF-8 mode default
- Node.js documentation, File system, fsPromises.readFile(path[, options])
- Node.js documentation, Util, class TextDecoder, the fatal and ignoreBOM options
- Node.js documentation, Buffer, Buffers and character encodings, 'utf8'; buffer.constants.MAX_STRING_LENGTH
- Java SE 25 API, java.nio.file.Files, readString(Path), readAllBytes(Path)
- .NET API reference, File.ReadAllText, Remarks
- .NET API reference, File.ReadAllBytes
- Go standard library, package os, func ReadFile
- The Rust Standard Library, std::fs::read_to_string, Errors
- The Rust Standard Library, std::fs::read
- The Open Group, POSIX.1-2024, fread, Return Value
- The Open Group, POSIX.1-2024, fopen, Errors, EISDIR
- The Open Group, POSIX.1-2024, sys/stat.h, st_size
- cppreference.com, std::istreambuf_iterator
- cppreference.com, std::basic_ifstream
- GNU Bash Reference Manual, Command Substitution
- PowerShell 7.6 reference, Get-Content, -Raw
- F. Yergeau, RFC 3629, UTF-8, a transformation format of ISO 10646 (2003), Section 3 and Section 10
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 GBTP51 Edit this page History Report an error Markdown