Programming Search⌘K

Taskcore

Read a binary file

Also called read the bytes of a file, read a file into a byte array, read a file in binary mode, read exactly n bytes.

Read the bytes of a file with no text decoding and no change to line ends or 0 bytes, and read exactly the first n bytes, with an error if the file ends first.

Task

Read a file as bytes. Give back each byte of the file in its order, with no text decoding. A CR LF stays CR LF, a 0 byte stays a 0 byte, and bytes that are not valid UTF-8 stay as they are.

Then read a fixed number of bytes: give back exactly the first n bytes of the file. If the file ends before byte n, report an error and give back no bytes. Programs do this to read the header of a file format, for example the 8-byte signature at the start of a PNG file.

If the file does not exist, or if the path names a directory, report an error.

The file must be small enough to keep in memory. To read a large file part by part, see Read and write with buffers. To read text, see Read a whole file. SQL, regular expressions, HTML and CSS do not apply, because none of them can open a file.

Solutions

Each solution has two functions: read_bytes(path) reads all of the file, and read_exact(path, n) reads the first n bytes. Each one returns a byte array, not a string.

  • Python. open(path, "rb").read(). "Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding." For read_exact, the code calls read again until it has n bytes, because BufferedIOBase.read says "Fewer bytes may be returned than requested". An empty result means the end of the file, and the code raises EOFError.
  • JavaScript and TypeScript (Node.js). fsPromises.readFile(path) with no encoding. "If no encoding is specified (using options.encoding), the data is returned as a object." For read_exact, the code calls filehandle.read in a loop. A bytesRead of 0 is the end of the file, and the code throws UnexpectedEofError.
  • Java. Files.readAllBytes(path). For read_exact, Files.newInputStream(path).readNBytes(n), which "blocks until the requested number of bytes has been read, end of stream is detected, or an exception is thrown". If the result is shorter than n, the code throws EOFException.
  • C#. File.ReadAllBytes(path). For read_exact, a FileStream and Stream.ReadExactly(buffer), which throws EndOfStreamException when "The end of the stream is reached before filling the buffer".
  • Go. os.ReadFile(path). For read_exact, os.Open and io.ReadFull(f, buf). io.ReadFull gives io.EOF when it reads no byte at all, so the code changes io.EOF to io.ErrUnexpectedEOF. Then each short file gives the same error.
  • Rust. std::fs::read(path) gives a Vec<u8>. For read_exact, File::open(path)?.read_exact(&mut buf). If the file ends first, the error is of kind ErrorKind::UnexpectedEof.
  • C. fopen(path, "rb"), fstat to reject a directory with EISDIR, then fread into a buffer that grows. The function returns the buffer and its length, because the bytes can hold 0 bytes and strlen cannot count them. read_exact calls fread once: POSIX says that fread returns fewer elements "only if an error or end-of-file is encountered", and ferror tells which. It returns READ_EXACT_EOF for a short file.
  • C++. std::ifstream(path, std::ios::binary) and read into a std::vector<std::byte>. gcount() gives the number of bytes that read got. The code returns std::expected<std::vector<std::byte>, ReadError> (C++23), with ReadError::unexpected_eof for a short file.
  • Bash. A Bash variable cannot hold a 0 byte, so the Bash functions store the bytes as hexadecimal text, two digits for each byte. od -An -v -tx1 writes each byte in hexadecimal with no offsets, and -N n stops after n bytes. The function read_exact returns status 2 when od gives fewer than 2n digits.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl, with the files in fixtures/. Each expected result is the bytes in lowercase hexadecimal. The cases of read_exact are in cases/exact.jsonl, and the cases that must give an error are in cases/errors.jsonl. The file .gitattributes marks the fixtures as -text, so Git does not change their line ends.

  • signature: the first 16 bytes of a PNG file. The signature holds \r\n, the byte 0x1A and a lone \n, so that a text transfer changes it. The PNG specification says: "The CR-LF sequence catches bad file transfers that alter newline sequences."
  • empty: the file has no bytes. read_bytes gives an empty array, not an error.
  • all-bytes: the 256 byte values from 0x00 to 0xFF, in order.
  • zeros: 8 bytes of 0x00.
  • crlf: a\r\nb\r\n. Each \r stays.
  • ctrl-z: a, the byte 0x1A, then b. In text mode on Windows, the C runtime reads 0x1A as the end of the file.
  • not-utf8: bytes that are not valid UTF-8, such as 0xFF and 0xFE. No decoder may see them.
  • read_exact cases: the first 8 bytes of the signature, the first 4 bytes, exactly all of the file, n = 0 on an empty file, and 3 bytes across 0x1A.
  • Errors: a missing file, a directory, n = 17 on the 16-byte signature file, and n = 1 on an empty file.

The native tests also read a file of 1 MiB. The Python, Go and C tests read 8 bytes from a named pipe that gets abc first and defgh 0.2 seconds later. One read call gets only abc, so a read_exact with no loop fails this test.

Pitfalls

  • Text mode. A file that is open in text mode goes through a decoder and, in Python, through newline translation. Latin-1 accepts each byte, so there is no decode error here, but the \r of the PNG signature is lost:

This code runs but gives a wrong answer on purpose.

import os
import tempfile

path = os.path.join(tempfile.mkdtemp(), "image.png")
data = bytes.fromhex("89504e470d0a1a0a0000000d49484452")
with open(path, "wb") as out:
    out.write(data)

# Text mode with an encoding that accepts each byte: no decode error,
# but "\r\n" comes back as "\n".
with open(path, encoding="latin-1") as file:
    text = file.read()
print(len(data), len(text))
print(text.encode("latin-1")[:8].hex())
Output
16 15
89504e470a1a0a00

With UTF-8, the first byte 0x89 gives UnicodeDecodeError. Open the file with "rb":

import os
import tempfile

path = os.path.join(tempfile.mkdtemp(), "image.png")
data = bytes.fromhex("89504e470d0a1a0a0000000d49484452")
with open(path, "wb") as out:
    out.write(data)

with open(path, "rb") as file:
    got = file.read()
print(len(data), len(got))
print(got[:8].hex())
Output
16 16
89504e470d0a1a0a
  • Bytes in a string. In Node.js, readFile(path, "utf8") decodes the bytes. The Buffer documentation says that for bytes that are not valid UTF-8, "the Unicode replacement character U+FFFD � will be used to represent those errors". The string then does not give the old bytes back:

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(), "png-")), "image.png");
const data = Buffer.from("89504e470d0a1a0a0000000d49484452", "hex");
writeFileSync(path, data);

// The bytes go through a string and back.
const text = readFileSync(path, "utf8");
const back = Buffer.from(text, "utf8");
console.log(data.length, back.length);
console.log(back.subarray(0, 8).toString("hex"));
Output
16 18
efbfbd504e470d0a

The byte 0x89 became the 3 bytes ef bf bd of U+FFFD. Keep the bytes in a Buffer, a byte[] or a Vec<u8>, and do not put them in a string.

  • strlen on bytes. In C, a byte buffer is not a string. strlen and printf("%s") stop at the first 0 byte:

This code runs but gives a wrong answer on purpose.

#include <stdio.h>
#include <string.h>

int main(void) {
    const unsigned char data[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
                                  0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52};
    FILE *out = tmpfile();
    if (out == NULL) return 1;
    fwrite(data, 1, sizeof data, out);
    rewind(out);

    char buf[64] = {0};
    size_t n = fread(buf, 1, sizeof buf, out);
    fclose(out);
    // strlen stops at the first 0 byte.
    printf("%zu %zu\n", n, strlen(buf));
    return 0;
}
Output
16 8

Keep the count that fread returns, and pass it with the buffer.

  • Text mode in C on Windows. On POSIX systems, the b in "rb" "shall have no effect". On Windows it matters. The Microsoft C runtime says that in text mode, "Carriage return-line feed (CR-LF) combinations are translated into single line feeds (LF) on input", and "CTRL+Z is interpreted as an end-of-file character on input". So fopen(path, "r") can stop at the byte 0x1A and drop each \r. Code that works on Linux can then fail on Windows. Always give "rb", and std::ios::binary in C++.
  • One read call is not enough. A read call can give fewer bytes than it asks for, before the end of the file. This is usual for pipes, sockets and terminals:

This code runs but gives a wrong answer on purpose.

import os

r, w = os.pipe()
os.write(w, b"abc")  # the first part of 8 bytes
data = os.read(r, 8)
print(len(data), data)
Output
3 b'abc'

Java InputStream.read(byte[]) "Reads some number of bytes". .NET Stream.Read returns a count that "can be less than the number of bytes requested". Use the call that reads again: readNBytes, ReadExactly, io.ReadFull, read_exact, or a loop that stops only when a read gives 0 bytes.

  • io.EOF from io.ReadFull. In Go, io.ReadFull gives io.ErrUnexpectedEOF for a short input, but "The error is EOF only if no bytes were read". Code that checks only for io.ErrUnexpectedEOF misses an empty file:

This code runs but gives a wrong answer on purpose.

package main

import (
	"errors"
	"fmt"
	"io"
	"strings"
)

func main() {
	// An empty input: ReadFull reads no byte, so the error is io.EOF.
	_, err := io.ReadFull(strings.NewReader(""), make([]byte, 4))
	fmt.Println(errors.Is(err, io.ErrUnexpectedEOF), err)
	// Two of four bytes: now the error is io.ErrUnexpectedEOF.
	_, err = io.ReadFull(strings.NewReader("ab"), make([]byte, 4))
	fmt.Println(errors.Is(err, io.ErrUnexpectedEOF), err)
}
Output
false EOF
true unexpected EOF
  • 0 bytes in a Bash variable. Bash drops each 0 byte when it stores the output of a command in a variable:

This code runs but gives a wrong answer on purpose.

file=$(mktemp)
printf 'a\0b' >"$file"
# Some versions of Bash also print a warning here.
{ text=$(<"$file"); } 2>/dev/null
printf '%s %s\n' "$(wc -c <"$file" | tr -d ' ')" "${#text}"
rm -f -- "$file"
Output
3 2

The file has 3 bytes, but the variable has 2 characters. Keep binary data in files and pipes, or change it to hexadecimal with od first.

  • A very large file. readAllBytes and the other functions here keep all of the file in memory. Java Files.readAllBytes throws OutOfMemoryError "if an array of the required size cannot be allocated, for example the file is larger that 2GB". For a large file, read a part at a time, as in Read and write with buffers.

Code

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

read_bytes.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-binary-file/.

import os


def read_bytes(path: str | os.PathLike[str]) -> bytes:
    """Return all of the bytes of a file, with no decoding."""
    # "rb" is binary mode: no decoding and no change to line ends.
    with open(path, "rb") as file:
        return file.read()


def read_exact(path: str | os.PathLike[str], n: int) -> bytes:
    """Return the first n bytes of a file, or raise EOFError if it is shorter."""
    data = bytearray()
    with open(path, "rb") as file:
        # read(k) can give fewer than k bytes before the end of the file,
        # so read again until there are n bytes or read gives b"".
        while len(data) < n:
            chunk = file.read(n - len(data))
            if not chunk:
                raise EOFError(f"{os.fspath(path)}: {len(data)} of {n} bytes before the end of the file")
            data += chunk
    return bytes(data)
test_read_bytes.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-binary-file/.

import os
import threading
import time
from pathlib import Path

import pytest

from read_bytes import read_bytes, read_exact

CASES = {
    "signature": bytes.fromhex("89504e470d0a1a0a0000000d49484452"),
    "bytes": bytes.fromhex("0001027f80feff"),
    "empty": b"",
    "all-bytes": bytes(range(256)),
    "zeros": bytes(8),
    "crlf": b"a\r\nb\r\n",
    "ctrl-z": b"a\x1ab",
    "not-utf8": bytes.fromhex("c328fffe80"),
    "large": bytes(range(256)) * 4096,
}

EXACT = {
    "signature-only": ("signature", 8, bytes.fromhex("89504e470d0a1a0a")),
    "first-four": ("all-bytes", 4, b"\x00\x01\x02\x03"),
    "whole-file": ("zeros", 8, bytes(8)),
    "zero-count": ("empty", 0, b""),
    "across-ctrl-z": ("ctrl-z", 3, b"a\x1ab"),
    "large": ("large", 1 << 20, CASES["large"]),
}

SHORT = {
    "one-past-end": ("signature", 17),
    "empty-file": ("empty", 1),
}


def write(tmp_path: Path, data: bytes) -> Path:
    path = tmp_path / "input.bin"
    path.write_bytes(data)
    return path


@pytest.mark.parametrize("name", CASES)
def test_read_bytes(tmp_path: Path, name: str) -> None:
    assert read_bytes(write(tmp_path, CASES[name])) == CASES[name]


@pytest.mark.parametrize("name", EXACT)
def test_read_exact(tmp_path: Path, name: str) -> None:
    data, n, want = EXACT[name]
    assert read_exact(write(tmp_path, CASES[data]), n) == want


@pytest.mark.parametrize("name", SHORT)
def test_short_file(tmp_path: Path, name: str) -> None:
    data, n = SHORT[name]
    with pytest.raises(EOFError):
        read_exact(write(tmp_path, CASES[data]), n)


@pytest.mark.parametrize("read", [read_bytes, lambda p: read_exact(p, 1)])
def test_missing_file(tmp_path: Path, read) -> None:
    with pytest.raises(FileNotFoundError):
        read(tmp_path / "missing.bin")


@pytest.mark.parametrize("read", [read_bytes, lambda p: read_exact(p, 1)])
def test_directory(tmp_path: Path, read) -> None:
    with pytest.raises(IsADirectoryError):
        read(tmp_path)


def test_read_exact_reads_again(tmp_path: Path) -> None:
    # A pipe gives the bytes in two parts, so one read call gets only the
    # first part. read_exact must read again to get all 8 bytes.
    fifo = tmp_path / "fifo"
    os.mkfifo(fifo)

    def writer() -> None:
        with open(fifo, "wb", buffering=0) as out:
            out.write(b"abc")
            time.sleep(0.2)
            out.write(b"defgh")

    thread = threading.Thread(target=writer)
    thread.start()
    try:
        assert read_exact(fifo, 8) == b"abcdefgh"
    finally:
        thread.join()
read_bytes.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.
// since: C++23 (std::expected)

#include "read_bytes.hpp"

#include <fstream>
#include <ios>
#include <system_error>

namespace {

// Opens path for binary reading. An ifstream opens a directory with no
// error on Linux, so check the type of the file first.
std::expected<std::ifstream, ReadError> open_file(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);
    }
    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 or CTRL+Z
    if (!in) return std::unexpected(ReadError::cannot_open);
    return in;
}

// Reads up to n bytes into data and returns how many it read. read sets
// eofbit and failbit at the end of the file; gcount gives the count.
std::size_t read_into(std::ifstream& in, std::vector<std::byte>& data, std::size_t offset,
                      std::size_t n) {
    in.read(reinterpret_cast<char*>(data.data() + offset), static_cast<std::streamsize>(n));
    return static_cast<std::size_t>(in.gcount());
}

}  // namespace

std::expected<std::vector<std::byte>, ReadError> read_bytes(const std::filesystem::path& path) {
    auto in = open_file(path);
    if (!in) return std::unexpected(in.error());
    std::vector<std::byte> data;
    std::size_t size = 0;
    for (std::size_t chunk = 4096;; chunk *= 2) {
        data.resize(size + chunk);
        std::size_t got = read_into(*in, data, size, chunk);
        size += got;
        if (got < chunk) break;
    }
    if (in->bad()) return std::unexpected(ReadError::read_failed);
    data.resize(size);
    return data;
}

std::expected<std::vector<std::byte>, ReadError> read_exact(const std::filesystem::path& path,
                                                            std::size_t n) {
    auto in = open_file(path);
    if (!in) return std::unexpected(in.error());
    std::vector<std::byte> data(n);
    std::size_t got = read_into(*in, data, 0, n);
    if (in->bad()) return std::unexpected(ReadError::read_failed);
    if (got < n) return std::unexpected(ReadError::unexpected_eof);
    return data;
}
read_bytes.hpp 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.
// since: C++23 (std::expected)

#pragma once

#include <cstddef>
#include <expected>
#include <filesystem>
#include <vector>

enum class ReadError { not_found, not_a_file, cannot_open, read_failed, unexpected_eof };

// Reads all of the bytes of the file at path, with no change to them.
std::expected<std::vector<std::byte>, ReadError> read_bytes(const std::filesystem::path& path);

// Reads the first n bytes of the file at path. If the file has fewer than n
// bytes, the error is ReadError::unexpected_eof.
std::expected<std::vector<std::byte>, ReadError> read_exact(const std::filesystem::path& path,
                                                            std::size_t n);
test_read_bytes.cpp 103 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.

#include <cstddef>
#include <cstdio>
#include <fstream>
#include <map>
#include <string>
#include <string_view>
#include <tuple>
#include <vector>

#include "read_bytes.hpp"

namespace {

const std::filesystem::path input = "read_bytes_input.bin";

using Bytes = std::vector<std::byte>;

Bytes hex(std::string_view s) {
    Bytes b;
    for (std::size_t i = 0; i + 1 < s.size(); i += 2) {
        b.push_back(static_cast<std::byte>(std::stoi(std::string(s.substr(i, 2)), nullptr, 16)));
    }
    return b;
}

Bytes pattern(std::size_t n) {
    Bytes b(n);
    for (std::size_t i = 0; i < n; ++i) b[i] = static_cast<std::byte>(i);
    return b;
}

void write_file(const Bytes& data) {
    std::ofstream out(input, std::ios::binary);
    out.write(reinterpret_cast<const char*>(data.data()), static_cast<std::streamsize>(data.size()));
}

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() {
    const std::map<std::string, Bytes> data = {
        {"signature", hex("89504e470d0a1a0a0000000d49484452")},
        {"bytes", hex("0001027f80feff")},
        {"empty", {}},
        {"all-bytes", pattern(256)},
        {"zeros", Bytes(8)},
        {"crlf", hex("610d0a620d0a")},
        {"ctrl-z", hex("611a62")},
        {"not-utf8", hex("c328fffe80")},
        {"large", pattern(1 << 20)},
    };
    for (const auto& [name, bytes] : data) {
        write_file(bytes);
        auto got = read_bytes(input);
        check(name, got && *got == bytes);
    }

    const std::vector<std::tuple<std::string, std::string, std::size_t, Bytes>> exact = {
        {"signature-only", "signature", 8, hex("89504e470d0a1a0a")},
        {"first-four", "all-bytes", 4, hex("00010203")},
        {"whole-file", "zeros", 8, Bytes(8)},
        {"zero-count", "empty", 0, {}},
        {"across-ctrl-z", "ctrl-z", 3, hex("611a62")},
        {"large", "large", 1 << 20, pattern(1 << 20)},
    };
    for (const auto& [name, file, n, want] : exact) {
        write_file(data.at(file));
        auto got = read_exact(input, n);
        check(name, got && *got == want);
    }

    for (const auto& [name, file, n] : {std::tuple{"one-past-end", "signature", 17},
                                        std::tuple{"empty-file", "empty", 1}}) {
        write_file(data.at(file));
        auto got = read_exact(input, n);
        check(name, !got && got.error() == ReadError::unexpected_eof);
    }

    std::filesystem::remove(input);
    auto missing = read_bytes("no_such_file.bin");
    check("missing", !missing && missing.error() == ReadError::not_found);
    auto missing_exact = read_exact("no_such_file.bin", 1);
    check("exact-missing", !missing_exact && missing_exact.error() == ReadError::not_found);
    auto dir = read_bytes(".");
    check("directory", !dir && dir.error() == ReadError::not_a_file);
    auto dir_exact = read_exact(".", 1);
    check("exact-directory", !dir_exact && dir_exact.error() == ReadError::not_a_file);

    if (failures > 0) return 1;
    std::puts("all tests passed");
    return 0;
}
ReadBytes.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

public final class ReadBytes {
  private ReadBytes() {}

  /** Returns all of the bytes of a file, with no decoding. */
  public static byte[] readBytes(Path path) throws IOException {
    return Files.readAllBytes(path);
  }

  /** Returns the first n bytes of a file, or throws EOFException if it is shorter. */
  public static byte[] readExact(Path path, int n) throws IOException {
    try (InputStream in = Files.newInputStream(path)) {
      // readNBytes reads again until it has n bytes or the stream ends.
      // read(byte[]) can stop after fewer bytes, so it is not enough.
      byte[] data = in.readNBytes(n);
      if (data.length < n) {
        throw new EOFException(path + ": " + data.length + " of " + n + " bytes before the end of the file");
      }
      return data;
    }
  }
}
ReadBytesTest.java 106 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.EOFException;
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.HexFormat;
import java.util.Map;
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 ReadBytesTest {
  @TempDir Path dir;

  private static byte[] hex(String s) {
    return HexFormat.of().parseHex(s);
  }

  private static byte[] allBytes() {
    byte[] b = new byte[256];
    for (int i = 0; i < 256; i++) b[i] = (byte) i;
    return b;
  }

  private static byte[] large() {
    byte[] b = new byte[1 << 20];
    for (int i = 0; i < b.length; i++) b[i] = (byte) i;
    return b;
  }

  private static final Map<String, byte[]> DATA =
      Map.of(
          "signature", hex("89504e470d0a1a0a0000000d49484452"),
          "bytes", hex("0001027f80feff"),
          "empty", new byte[0],
          "all-bytes", allBytes(),
          "zeros", new byte[8],
          "crlf", "a\r\nb\r\n".getBytes(StandardCharsets.US_ASCII),
          "ctrl-z", hex("611a62"),
          "not-utf8", hex("c328fffe80"),
          "large", large());

  private Path write(String name) throws IOException {
    return Files.write(dir.resolve("input.bin"), DATA.get(name));
  }

  static Stream<String> cases() {
    return DATA.keySet().stream().sorted();
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void readsBytes(String name) throws IOException {
    assertArrayEquals(DATA.get(name), ReadBytes.readBytes(write(name)));
  }

  static Stream<Arguments> exact() {
    return Stream.of(
        Arguments.of("signature-only", "signature", 8, hex("89504e470d0a1a0a")),
        Arguments.of("first-four", "all-bytes", 4, hex("00010203")),
        Arguments.of("whole-file", "zeros", 8, new byte[8]),
        Arguments.of("zero-count", "empty", 0, new byte[0]),
        Arguments.of("across-ctrl-z", "ctrl-z", 3, hex("611a62")),
        Arguments.of("large", "large", 1 << 20, large()));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("exact")
  void readsExact(String name, String data, int n, byte[] want) throws IOException {
    assertArrayEquals(want, ReadBytes.readExact(write(data), n));
  }

  static Stream<Arguments> shortFiles() {
    return Stream.of(Arguments.of("one-past-end", "signature", 17), Arguments.of("empty-file", "empty", 1));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("shortFiles")
  void shortFile(String name, String data, int n) throws IOException {
    Path path = write(data);
    assertThrows(EOFException.class, () -> ReadBytes.readExact(path, n));
  }

  @Test
  void missingFile() {
    Path path = dir.resolve("missing.bin");
    assertThrows(NoSuchFileException.class, () -> ReadBytes.readBytes(path));
    assertThrows(NoSuchFileException.class, () -> ReadBytes.readExact(path, 1));
  }

  @Test
  void directory() {
    assertThrows(IOException.class, () -> ReadBytes.readBytes(dir));
    assertThrows(IOException.class, () -> ReadBytes.readExact(dir, 1));
  }
}
read_bytes.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.

// fileno and fstat are in POSIX.1-2008, not in ISO C.
#define _POSIX_C_SOURCE 200809L

#include "read_bytes.h"

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

// open_file opens path for binary reading and rejects a directory. On
// Windows, "rb" stops the C library from changing CR LF and from taking
// CTRL+Z as the end of the file; on POSIX systems the b has no effect.
static FILE *open_file(const char *path) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) return NULL;
    struct stat st;
    int err = 0;
    if (fstat(fileno(f), &st) != 0) {
        err = errno;
    } else if (S_ISDIR(st.st_mode)) {
        err = EISDIR;
    }
    if (err != 0) {
        fclose(f);
        errno = err;
        return NULL;
    }
    return f;
}

unsigned char *read_bytes(const char *path, size_t *len) {
    FILE *f = open_file(path);
    if (f == NULL) return NULL;

    int err = 0;
    size_t n = 0, cap = 4096;
    unsigned char *buf = malloc(cap);
    while (buf != NULL) {
        // fread gives fewer bytes than it was asked for only at the end of
        // the file or on an error. While the buffer fills, make it bigger.
        n += fread(buf + n, 1, cap - n, f);
        if (n < cap) break;
        unsigned 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;
    }
    fclose(f);
    if (err != 0) {
        free(buf);
        errno = err;
        return NULL;
    }
    *len = n;
    return buf;
}

enum read_exact_result read_exact(const char *path, unsigned char *buf, size_t n) {
    FILE *f = open_file(path);
    if (f == NULL) return READ_EXACT_ERROR;
    // POSIX says that fread gives fewer than n bytes only at the end of
    // the file or on an error, so one call is enough; ferror tells which.
    size_t got = fread(buf, 1, n, f);
    enum read_exact_result result = READ_EXACT_OK;
    int err = 0;
    if (got < n) {
        if (ferror(f)) {
            err = errno != 0 ? errno : EIO;
            result = READ_EXACT_ERROR;
        } else {
            result = READ_EXACT_EOF;
        }
    }
    fclose(f);
    if (err != 0) errno = err;
    return result;
}
read_bytes.h 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.

#ifndef READ_BYTES_H
#define READ_BYTES_H

#include <stddef.h>

// read_bytes reads all of the bytes of the file at path. It returns a new
// buffer that the caller must free, and stores the number of bytes in *len.
// The bytes can hold 0 bytes, so use *len and not strlen. For an empty file
// it returns a buffer that is not NULL and sets *len to 0. On an error it
// returns NULL and sets errno: EISDIR for a directory, or the error of
// fopen, fstat or fread.
unsigned char *read_bytes(const char *path, size_t *len);

// The results of read_exact.
enum read_exact_result {
    READ_EXACT_OK = 0,     // buf holds the first n bytes of the file
    READ_EXACT_ERROR = -1, // an error; errno tells which
    READ_EXACT_EOF = -2,   // the file has fewer than n bytes
};

// read_exact reads the first n bytes of the file at path into buf, which
// must have room for n bytes. On READ_EXACT_ERROR, errno is EISDIR for a
// directory or the error of fopen, fstat or fread. On an error or
// READ_EXACT_EOF, the contents of buf are not specified.
enum read_exact_result read_exact(const char *path, unsigned char *buf, size_t n);

#endif
test_read_bytes.c 147 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.

// mkfifo, fork and waitpid are in POSIX.1-2008, not in ISO C.
#define _POSIX_C_SOURCE 200809L

#include "read_bytes.h"

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

static const char *path = "read_bytes_input.bin";

static void write_file(const unsigned 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 unsigned char *data, size_t n) {
    write_file(data, n);
    size_t len = 99;
    unsigned char *got = read_bytes(path, &len);
    if (got == NULL || len != n || memcmp(got, data, n) != 0) {
        fprintf(stderr, "case %s: wrong bytes\n", name);
        exit(1);
    }
    free(got);
}

static void check_exact(const char *name, const unsigned char *data, size_t size, size_t n) {
    write_file(data, size);
    unsigned char *buf = malloc(n > 0 ? n : 1);
    assert(buf != NULL);
    if (read_exact(path, buf, n) != READ_EXACT_OK || memcmp(buf, data, n) != 0) {
        fprintf(stderr, "case %s: wrong bytes\n", name);
        exit(1);
    }
    free(buf);
}

static void check_short(const char *name, const unsigned char *data, size_t size, size_t n) {
    write_file(data, size);
    unsigned char buf[32];
    assert(n <= sizeof buf);
    if (read_exact(path, buf, n) != READ_EXACT_EOF) {
        fprintf(stderr, "case %s: want READ_EXACT_EOF\n", name);
        exit(1);
    }
}

static void check_error(const char *name, const char *file, int want) {
    size_t len;
    unsigned char buf[1];
    errno = 0;
    if (read_bytes(file, &len) != NULL || errno != want) {
        fprintf(stderr, "case %s: read_bytes: want errno %d, got %d\n", name, want, errno);
        exit(1);
    }
    errno = 0;
    if (read_exact(file, buf, 1) != READ_EXACT_ERROR || errno != want) {
        fprintf(stderr, "case %s: read_exact: want errno %d, got %d\n", name, want, errno);
        exit(1);
    }
}

// A pipe gives the bytes in two parts, so one read call gets only the first
// part. read_exact must read again to get all 8 bytes.
static void check_reads_again(void) {
    const char *fifo = "read_bytes_fifo";
    remove(fifo);
    assert(mkfifo(fifo, 0600) == 0);
    pid_t pid = fork();
    assert(pid >= 0);
    if (pid == 0) {
        FILE *out = fopen(fifo, "wb");
        if (out == NULL) _exit(1);
        setvbuf(out, NULL, _IONBF, 0);
        fwrite("abc", 1, 3, out);
        nanosleep(&(struct timespec){.tv_nsec = 200000000}, NULL);
        fwrite("defgh", 1, 5, out);
        _exit(fclose(out) == 0 ? 0 : 1);
    }
    unsigned char buf[8];
    enum read_exact_result r = read_exact(fifo, buf, 8);
    int status;
    assert(waitpid(pid, &status, 0) == pid && WIFEXITED(status) && WEXITSTATUS(status) == 0);
    remove(fifo);
    if (r != READ_EXACT_OK || memcmp(buf, "abcdefgh", 8) != 0) {
        fprintf(stderr, "case reads-again: wrong bytes\n");
        exit(1);
    }
}

#define BYTES(...) ((const unsigned char[]){__VA_ARGS__})
#define CASE(name, ...) check(name, BYTES(__VA_ARGS__), sizeof(BYTES(__VA_ARGS__)))

int main(void) {
    static const unsigned char signature[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
                                              0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52};
    unsigned char all[256];
    for (int i = 0; i < 256; i++) all[i] = (unsigned char)i;
    static const unsigned char zeros[8] = {0};
    static const unsigned char ctrl_z[] = {'a', 0x1a, 'b'};

    check("signature", signature, sizeof signature);
    CASE("bytes", 0x00, 0x01, 0x02, 0x7f, 0x80, 0xfe, 0xff);
    check("empty", all, 0);
    check("all-bytes", all, sizeof all);
    check("zeros", zeros, sizeof zeros);
    CASE("crlf", 'a', '\r', '\n', 'b', '\r', '\n');
    check("ctrl-z", ctrl_z, sizeof ctrl_z);
    CASE("not-utf8", 0xc3, 0x28, 0xff, 0xfe, 0x80);

    size_t big = 1 << 20;
    unsigned char *large = malloc(big);
    assert(large != NULL);
    for (size_t i = 0; i < big; i++) large[i] = (unsigned char)i;
    check("large", large, big);

    check_exact("signature-only", signature, sizeof signature, 8);
    check_exact("first-four", all, sizeof all, 4);
    check_exact("whole-file", zeros, sizeof zeros, 8);
    check_exact("zero-count", all, 0, 0);
    check_exact("across-ctrl-z", ctrl_z, sizeof ctrl_z, 3);
    check_exact("large", large, big, big);
    free(large);

    check_short("one-past-end", signature, sizeof signature, 17);
    check_short("empty-file", all, 0, 1);

    remove(path);
    check_error("missing", "no_such_file.bin", ENOENT);
    check_error("directory", ".", EISDIR);
    check_reads_again();

    puts("all tests passed");
    return 0;
}
ReadBytes.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.

public static class ReadBytes
{
    /// <summary>Returns all of the bytes of a file, with no decoding.</summary>
    public static byte[] Read(string path) => File.ReadAllBytes(path);

    /// <summary>Returns the first n bytes of a file.</summary>
    /// <exception cref="EndOfStreamException">The file has fewer than n bytes.</exception>
    public static byte[] ReadExact(string path, int n)
    {
        using var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
        var data = new byte[n];
        // ReadExactly reads again until the buffer is full. Read can stop
        // after fewer bytes, so its result must not be taken as n bytes.
        stream.ReadExactly(data);
        return data;
    }
}
ReadBytesTests.cs 82 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.

using Xunit;

public sealed class ReadBytesTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("read-bytes-").FullName;

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

    private static readonly Dictionary<string, byte[]> Data = new()
    {
        ["signature"] = Convert.FromHexString("89504e470d0a1a0a0000000d49484452"),
        ["bytes"] = Convert.FromHexString("0001027f80feff"),
        ["empty"] = [],
        ["all-bytes"] = Enumerable.Range(0, 256).Select(i => (byte)i).ToArray(),
        ["zeros"] = new byte[8],
        ["crlf"] = "a\r\nb\r\n"u8.ToArray(),
        ["ctrl-z"] = Convert.FromHexString("611a62"),
        ["not-utf8"] = Convert.FromHexString("c328fffe80"),
        ["large"] = Enumerable.Range(0, 1 << 20).Select(i => (byte)i).ToArray(),
    };

    private string Write(string name)
    {
        string path = Path.Combine(dir, "input.bin");
        File.WriteAllBytes(path, Data[name]);
        return path;
    }

    public static TheoryData<string> Cases => new(Data.Keys);

    [Theory]
    [MemberData(nameof(Cases))]
    public void ReadsBytes(string name) => Assert.Equal(Data[name], ReadBytes.Read(Write(name)));

    public static TheoryData<string, string, int, string> Exact => new()
    {
        { "signature-only", "signature", 8, "89504e470d0a1a0a" },
        { "first-four", "all-bytes", 4, "00010203" },
        { "whole-file", "zeros", 8, "0000000000000000" },
        { "zero-count", "empty", 0, "" },
        { "across-ctrl-z", "ctrl-z", 3, "611a62" },
    };

    [Theory]
    [MemberData(nameof(Exact))]
    public void ReadsExact(string name, string data, int n, string want)
    {
        Assert.Equal(Convert.FromHexString(want), ReadBytes.ReadExact(Write(data), n));
        Assert.False(string.IsNullOrEmpty(name));
    }

    [Fact]
    public void ReadsExactLarge() => Assert.Equal(Data["large"], ReadBytes.ReadExact(Write("large"), 1 << 20));

    [Theory]
    [InlineData("one-past-end", "signature", 17)]
    [InlineData("empty-file", "empty", 1)]
    public void ShortFile(string name, string data, int n)
    {
        string path = Write(data);
        Assert.Throws<EndOfStreamException>(() => ReadBytes.ReadExact(path, n));
        Assert.False(string.IsNullOrEmpty(name));
    }

    [Fact]
    public void MissingFile()
    {
        string path = Path.Combine(dir, "missing.bin");
        Assert.Throws<FileNotFoundException>(() => ReadBytes.Read(path));
        Assert.Throws<FileNotFoundException>(() => ReadBytes.ReadExact(path, 1));
    }

    [Fact]
    public void PathIsADirectory()
    {
        Assert.Throws<UnauthorizedAccessException>(() => ReadBytes.Read(dir));
        Assert.Throws<UnauthorizedAccessException>(() => ReadBytes.ReadExact(dir, 1));
    }
}
readBytes.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.

import { open, readFile } from "node:fs/promises";

/** The error of readExact when the file ends before byte n. */
export class UnexpectedEofError extends Error {
  constructor(path, got, n) {
    super(`${path}: ${got} of ${n} bytes before the end of the file`);
    this.name = "UnexpectedEofError";
  }
}

/** Return all of the bytes of a file as a Buffer, with no decoding. */
export async function readBytes(path) {
  // With no encoding option, readFile gives a Buffer and not a string.
  return readFile(path);
}

/** Return the first n bytes of a file, or throw UnexpectedEofError if it is shorter. */
export async function readExact(path, n) {
  const buffer = Buffer.alloc(n);
  const file = await open(path, "r");
  try {
    let got = 0;
    while (got < n) {
      // One read can give fewer bytes than it asks for, so read again.
      const { bytesRead } = await file.read(buffer, got, n - got, null);
      if (bytesRead === 0) throw new UnexpectedEofError(path, got, n);
      got += bytesRead;
    }
    return buffer;
  } finally {
    await file.close();
  }
}
readBytes.test.js 84 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-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 { readBytes, readExact, UnexpectedEofError } from "./readBytes.js";

const hex = (s) => Buffer.from(s, "hex");
const allBytes = Buffer.from(Array.from({ length: 256 }, (_, i) => i));

const cases = {
  signature: hex("89504e470d0a1a0a0000000d49484452"),
  bytes: hex("0001027f80feff"),
  empty: Buffer.alloc(0),
  "all-bytes": allBytes,
  zeros: Buffer.alloc(8),
  crlf: Buffer.from("a\r\nb\r\n", "latin1"),
  "ctrl-z": hex("611a62"),
  "not-utf8": hex("c328fffe80"),
  large: Buffer.concat(Array(4096).fill(allBytes)),
};

const exact = {
  "signature-only": ["signature", 8, hex("89504e470d0a1a0a")],
  "first-four": ["all-bytes", 4, hex("00010203")],
  "whole-file": ["zeros", 8, Buffer.alloc(8)],
  "zero-count": ["empty", 0, Buffer.alloc(0)],
  "across-ctrl-z": ["ctrl-z", 3, hex("611a62")],
  large: ["large", 1 << 20, cases.large],
};

const short = {
  "one-past-end": ["signature", 17],
  "empty-file": ["empty", 1],
};

async function withFile(data, body) {
  const dir = await mkdtemp(join(tmpdir(), "read-bytes-"));
  try {
    const path = join(dir, "input.bin");
    if (data !== undefined) await writeFile(path, data);
    await body(path, dir);
  } finally {
    await rm(dir, { recursive: true, force: true });
  }
}

for (const [name, data] of Object.entries(cases)) {
  test(`readBytes ${name}`, () =>
    withFile(data, async (path) => {
      const got = await readBytes(path);
      assert.ok(Buffer.isBuffer(got));
      assert.deepEqual(got, data);
    }));
}

for (const [name, [data, n, want]] of Object.entries(exact)) {
  test(`readExact ${name}`, () =>
    withFile(cases[data], async (path) => {
      assert.deepEqual(await readExact(path, n), want);
    }));
}

for (const [name, [data, n]] of Object.entries(short)) {
  test(`readExact ${name}`, () =>
    withFile(cases[data], async (path) => {
      await assert.rejects(readExact(path, n), UnexpectedEofError);
    }));
}

test("missing file", () =>
  withFile(undefined, async (path) => {
    await assert.rejects(readBytes(path), { code: "ENOENT" });
    await assert.rejects(readExact(path, 1), { code: "ENOENT" });
  }));

test("directory", () =>
  withFile(undefined, async (_, dir) => {
    await assert.rejects(readBytes(dir), { code: "EISDIR" });
    await assert.rejects(readExact(dir, 1), { code: "EISDIR" });
  }));
readBytes.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.

import { open, readFile } from "node:fs/promises";

/** The error of readExact when the file ends before byte n. */
export class UnexpectedEofError extends Error {
  constructor(path: string, got: number, n: number) {
    super(`${path}: ${got} of ${n} bytes before the end of the file`);
    this.name = "UnexpectedEofError";
  }
}

/** Return all of the bytes of a file as a Buffer, with no decoding. */
export async function readBytes(path: string): Promise<Buffer> {
  // With no encoding option, readFile gives a Buffer and not a string.
  return readFile(path);
}

/** Return the first n bytes of a file, or throw UnexpectedEofError if it is shorter. */
export async function readExact(path: string, n: number): Promise<Buffer> {
  const buffer = Buffer.alloc(n);
  const file = await open(path, "r");
  try {
    let got = 0;
    while (got < n) {
      // One read can give fewer bytes than it asks for, so read again.
      const { bytesRead } = await file.read(buffer, got, n - got, null);
      if (bytesRead === 0) throw new UnexpectedEofError(path, got, n);
      got += bytesRead;
    }
    return buffer;
  } finally {
    await file.close();
  }
}
readBytes.test.ts 87 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-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 { readBytes, readExact, UnexpectedEofError } from "./readBytes.ts";

const hex = (s: string): Buffer => Buffer.from(s, "hex");
const allBytes = Buffer.from(Array.from({ length: 256 }, (_, i) => i));

const cases: Record<string, Buffer> = {
  signature: hex("89504e470d0a1a0a0000000d49484452"),
  bytes: hex("0001027f80feff"),
  empty: Buffer.alloc(0),
  "all-bytes": allBytes,
  zeros: Buffer.alloc(8),
  crlf: Buffer.from("a\r\nb\r\n", "latin1"),
  "ctrl-z": hex("611a62"),
  "not-utf8": hex("c328fffe80"),
  large: Buffer.concat(Array(4096).fill(allBytes)),
};

const exact: Record<string, [string, number, Buffer]> = {
  "signature-only": ["signature", 8, hex("89504e470d0a1a0a")],
  "first-four": ["all-bytes", 4, hex("00010203")],
  "whole-file": ["zeros", 8, Buffer.alloc(8)],
  "zero-count": ["empty", 0, Buffer.alloc(0)],
  "across-ctrl-z": ["ctrl-z", 3, hex("611a62")],
  large: ["large", 1 << 20, cases.large],
};

const short: Record<string, [string, number]> = {
  "one-past-end": ["signature", 17],
  "empty-file": ["empty", 1],
};

async function withFile(
  data: Buffer | undefined,
  body: (path: string, dir: string) => Promise<void>,
): Promise<void> {
  const dir = await mkdtemp(join(tmpdir(), "read-bytes-"));
  try {
    const path = join(dir, "input.bin");
    if (data !== undefined) await writeFile(path, data);
    await body(path, dir);
  } finally {
    await rm(dir, { recursive: true, force: true });
  }
}

for (const [name, data] of Object.entries(cases)) {
  test(`readBytes ${name}`, () =>
    withFile(data, async (path) => {
      const got = await readBytes(path);
      assert.ok(Buffer.isBuffer(got));
      assert.deepEqual(got, data);
    }));
}

for (const [name, [data, n, want]] of Object.entries(exact)) {
  test(`readExact ${name}`, () =>
    withFile(cases[data], async (path) => {
      assert.deepEqual(await readExact(path, n), want);
    }));
}

for (const [name, [data, n]] of Object.entries(short)) {
  test(`readExact ${name}`, () =>
    withFile(cases[data], async (path) => {
      await assert.rejects(readExact(path, n), UnexpectedEofError);
    }));
}

test("missing file", () =>
  withFile(undefined, async (path) => {
    await assert.rejects(readBytes(path), { code: "ENOENT" });
    await assert.rejects(readExact(path, 1), { code: "ENOENT" });
  }));

test("directory", () =>
  withFile(undefined, async (_, dir) => {
    await assert.rejects(readBytes(dir), { code: "EISDIR" });
    await assert.rejects(readExact(dir, 1), { code: "EISDIR" });
  }));
read_bytes.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.

// Package readbytes reads the bytes of a file with no text decoding.
package readbytes

import (
	"errors"
	"io"
	"os"
)

// ReadBytes returns all of the bytes of the file at path.
func ReadBytes(path string) ([]byte, error) {
	return os.ReadFile(path)
}

// ReadExact returns the first n bytes of the file at path. If the file has
// fewer than n bytes, the error is io.ErrUnexpectedEOF.
func ReadExact(path string, n int) ([]byte, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	data := make([]byte, n)
	// io.ReadFull calls Read again until data is full. It gives io.EOF when
	// it reads no byte at all, so treat that as a short file too.
	if _, err := io.ReadFull(f, data); err != nil {
		if errors.Is(err, io.EOF) {
			err = io.ErrUnexpectedEOF
		}
		return nil, err
	}
	return data, nil
}
read_bytes_test.go 158 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.

package readbytes

import (
	"bytes"
	"encoding/hex"
	"errors"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"syscall"
	"testing"
	"time"
)

func unhex(s string) []byte {
	b, err := hex.DecodeString(s)
	if err != nil {
		panic(err)
	}
	return b
}

func pattern(n int) []byte {
	b := make([]byte, n)
	for i := range b {
		b[i] = byte(i)
	}
	return b
}

var data = map[string][]byte{
	"signature": unhex("89504e470d0a1a0a0000000d49484452"),
	"bytes":     unhex("0001027f80feff"),
	"empty":     {},
	"all-bytes": pattern(256),
	"zeros":     make([]byte, 8),
	"crlf":      []byte("a\r\nb\r\n"),
	"ctrl-z":    unhex("611a62"),
	"not-utf8":  unhex("c328fffe80"),
	"large":     pattern(1 << 20),
}

func write(t *testing.T, name string) string {
	t.Helper()
	path := filepath.Join(t.TempDir(), "input.bin")
	if err := os.WriteFile(path, data[name], 0o644); err != nil {
		t.Fatal(err)
	}
	return path
}

func TestReadBytes(t *testing.T) {
	for name, want := range data {
		t.Run(name, func(t *testing.T) {
			got, err := ReadBytes(write(t, name))
			if err != nil || !bytes.Equal(got, want) {
				t.Fatalf("ReadBytes = %x, %v; want %x", got, err, want)
			}
		})
	}
}

func TestReadExact(t *testing.T) {
	cases := []struct {
		name, data string
		n          int
		want       []byte
	}{
		{"signature-only", "signature", 8, unhex("89504e470d0a1a0a")},
		{"first-four", "all-bytes", 4, unhex("00010203")},
		{"whole-file", "zeros", 8, make([]byte, 8)},
		{"zero-count", "empty", 0, []byte{}},
		{"across-ctrl-z", "ctrl-z", 3, unhex("611a62")},
		{"large", "large", 1 << 20, data["large"]},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, err := ReadExact(write(t, c.data), c.n)
			if err != nil || !bytes.Equal(got, c.want) {
				t.Fatalf("ReadExact = %x, %v; want %x", got, err, c.want)
			}
		})
	}
}

func TestShortFile(t *testing.T) {
	cases := []struct {
		name, data string
		n          int
	}{
		{"one-past-end", "signature", 17},
		{"empty-file", "empty", 1},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			_, err := ReadExact(write(t, c.data), c.n)
			if !errors.Is(err, io.ErrUnexpectedEOF) {
				t.Fatalf("err = %v; want io.ErrUnexpectedEOF", err)
			}
		})
	}
}

func TestMissingFile(t *testing.T) {
	path := filepath.Join(t.TempDir(), "missing.bin")
	if _, err := ReadBytes(path); !errors.Is(err, fs.ErrNotExist) {
		t.Fatalf("ReadBytes err = %v; want fs.ErrNotExist", err)
	}
	if _, err := ReadExact(path, 1); !errors.Is(err, fs.ErrNotExist) {
		t.Fatalf("ReadExact err = %v; want fs.ErrNotExist", err)
	}
}

func TestDirectory(t *testing.T) {
	dir := t.TempDir()
	if _, err := ReadBytes(dir); !errors.Is(err, syscall.EISDIR) {
		t.Fatalf("ReadBytes err = %v; want EISDIR", err)
	}
	if _, err := ReadExact(dir, 1); !errors.Is(err, syscall.EISDIR) {
		t.Fatalf("ReadExact err = %v; want EISDIR", err)
	}
}

// A pipe gives the bytes in two parts, so one Read call gets only the first
// part. ReadExact must read again to get all 8 bytes.
func TestReadsAgain(t *testing.T) {
	fifo := filepath.Join(t.TempDir(), "fifo")
	if err := syscall.Mkfifo(fifo, 0o600); err != nil {
		t.Fatal(err)
	}
	done := make(chan error, 1)
	go func() {
		out, err := os.OpenFile(fifo, os.O_WRONLY, 0)
		if err != nil {
			done <- err
			return
		}
		defer out.Close()
		if _, err := out.Write([]byte("abc")); err != nil {
			done <- err
			return
		}
		time.Sleep(200 * time.Millisecond)
		_, err = out.Write([]byte("defgh"))
		done <- err
	}()
	got, err := ReadExact(fifo, 8)
	if werr := <-done; werr != nil {
		t.Fatal(werr)
	}
	if err != nil || string(got) != "abcdefgh" {
		t.Fatalf("ReadExact = %q, %v; want abcdefgh", got, err)
	}
}
read_bytes.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.

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

/// Returns all of the bytes of a file, with no decoding.
pub fn read_bytes(path: impl AsRef<Path>) -> io::Result<Vec<u8>> {
    fs::read(path)
}

/// Returns the first `n` bytes of a file.
///
/// If the file has fewer than `n` bytes, the error is of kind
/// `UnexpectedEof`. `read_exact` calls `read` again until the buffer is
/// full; one call to `read` can give fewer bytes than it asks for.
pub fn read_exact(path: impl AsRef<Path>, n: usize) -> io::Result<Vec<u8>> {
    let mut data = vec![0; n];
    File::open(path)?.read_exact(&mut data)?;
    Ok(data)
}
tests/read_bytes_test.rs 90 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-a-binary-file/.

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

use algo_read_a_binary_file::{read_bytes, read_exact};

/// Returns a new empty directory for one test.
fn temp_dir(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("read-bytes-{}-{name}", std::process::id()));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    dir
}

fn hex(s: &str) -> Vec<u8> {
    (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect()
}

fn pattern(n: usize) -> Vec<u8> {
    (0..n).map(|i| i as u8).collect()
}

fn data(name: &str) -> Vec<u8> {
    match name {
        "signature" => hex("89504e470d0a1a0a0000000d49484452"),
        "bytes" => hex("0001027f80feff"),
        "empty" => Vec::new(),
        "all-bytes" => pattern(256),
        "zeros" => vec![0; 8],
        "crlf" => b"a\r\nb\r\n".to_vec(),
        "ctrl-z" => hex("611a62"),
        "not-utf8" => hex("c328fffe80"),
        "large" => pattern(1 << 20),
        _ => panic!("no data {name}"),
    }
}

/// Writes the data of one case to a new file and returns its path.
fn write(test: &str, name: &str) -> PathBuf {
    let path = temp_dir(&format!("{test}-{name}")).join("input.bin");
    fs::write(&path, data(name)).unwrap();
    path
}

#[test]
fn reads_bytes() {
    for name in ["signature", "bytes", "empty", "all-bytes", "zeros", "crlf", "ctrl-z", "not-utf8", "large"] {
        assert_eq!(read_bytes(write("bytes", name)).unwrap(), data(name), "case {name}");
    }
}

#[test]
fn reads_exact() {
    let cases = [
        ("signature-only", "signature", 8, hex("89504e470d0a1a0a")),
        ("first-four", "all-bytes", 4, hex("00010203")),
        ("whole-file", "zeros", 8, vec![0; 8]),
        ("zero-count", "empty", 0, Vec::new()),
        ("across-ctrl-z", "ctrl-z", 3, hex("611a62")),
        ("large", "large", 1 << 20, pattern(1 << 20)),
    ];
    for (name, file, n, want) in cases {
        assert_eq!(read_exact(write("exact", file), n).unwrap(), want, "case {name}");
    }
}

#[test]
fn short_file() {
    for (name, file, n) in [("one-past-end", "signature", 17), ("empty-file", "empty", 1)] {
        let err = read_exact(write("short", file), n).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::UnexpectedEof, "case {name}");
    }
}

#[test]
fn missing_file() {
    let path = temp_dir("missing").join("missing.bin");
    assert_eq!(read_bytes(&path).unwrap_err().kind(), ErrorKind::NotFound);
    assert_eq!(read_exact(&path, 1).unwrap_err().kind(), ErrorKind::NotFound);
}

#[test]
fn directory() {
    let dir = temp_dir("directory");
    assert_eq!(read_bytes(&dir).unwrap_err().kind(), ErrorKind::IsADirectory);
    assert_eq!(read_exact(&dir, 1).unwrap_err().kind(), ErrorKind::IsADirectory);
}
read_bytes.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-binary-file/.

# A Bash variable cannot hold a 0 byte, so these functions give the bytes as
# lowercase hexadecimal, two digits for each byte, made by od.

# read_bytes NAME PATH
# Stores the bytes of the file PATH in the variable NAME, as hexadecimal.
# Returns status 1, and does not set NAME, if PATH is missing or a directory.
read_bytes() {
  local _read_bytes
  if [[ -d $2 ]]; then
    printf 'read_bytes: %s: is a directory\n' "$2" >&2
    return 1
  fi
  # -An: no offsets; -v: no * for lines that repeat; -tx1: one byte at a time.
  _read_bytes=$(set -o pipefail; od -An -v -tx1 -- "$2" | tr -d ' \n') || return 1
  printf -v "$1" '%s' "$_read_bytes"
}

# read_exact NAME PATH N
# Stores the first N bytes of the file PATH in the variable NAME, as
# hexadecimal. Returns status 1 if PATH is missing or a directory, and
# status 2 if the file has fewer than N bytes. NAME is not set on an error.
read_exact() {
  local _read_exact=''
  if [[ -d $2 ]]; then
    printf 'read_exact: %s: is a directory\n' "$2" >&2
    return 1
  fi
  if (($3 > 0)); then
    # -N stops od after N bytes; a shorter file gives fewer digits.
    _read_exact=$(set -o pipefail; od -An -v -tx1 -N "$3" -- "$2" | tr -d ' \n') || return 1
  elif [[ ! -r $2 ]]; then
    printf 'read_exact: %s: cannot read the file\n' "$2" >&2
    return 1
  fi
  if ((${#_read_exact} < 2 * $3)); then
    printf 'read_exact: %s: %d of %d bytes before the end of the file\n' \
      "$2" $((${#_read_exact} / 2)) "$3" >&2
    return 2
  fi
  printf -v "$1" '%s' "$_read_exact"
}
test_read_bytes.bats 85 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-a-binary-file/.

bats_require_minimum_version 1.5.0

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

# write HEX: write the bytes that HEX names to the file.
write() {
  local hex=$1 esc=''
  while [[ -n $hex ]]; do
    esc+="\\x${hex:0:2}"
    hex=${hex:2}
  done
  printf "$esc" >"$file"
}

check() { # check HEX
  local got
  write "$1"
  read_bytes got "$file"
  [ "$got" = "$1" ]
}

check_exact() { # check_exact HEX N WANT
  local got
  write "$1"
  read_exact got "$file" "$2"
  [ "$got" = "$3" ]
}

all_bytes() {
  local i
  for ((i = 0; i < 256; i++)); do printf '%02x' "$i"; done
}

@test "signature" { check 89504e470d0a1a0a0000000d49484452; }
@test "bytes" { check 0001027f80feff; }
@test "empty" { check ''; }
@test "all-bytes" { check "$(all_bytes)"; }
@test "zeros" { check 0000000000000000; }
@test "crlf" { check 610d0a620d0a; }
@test "ctrl-z" { check 611a62; }
@test "not-utf8" { check c328fffe80; }

@test "large" {
  local got want
  want=$(all_bytes)
  for _ in 1 2 3 4 5 6 7 8 9 10 11 12; do want+=$want; done # 256 * 4096 bytes
  write "$(all_bytes)"
  for _ in 1 2 3 4 5 6 7 8 9 10 11 12; do cat "$file" "$file" >"$file.2" && mv "$file.2" "$file"; done
  read_bytes got "$file"
  [ "${#got}" -eq $((2 << 20)) ]
  [ "$got" = "$want" ]
}

@test "signature-only" { check_exact 89504e470d0a1a0a0000000d49484452 8 89504e470d0a1a0a; }
@test "first-four" { check_exact "$(all_bytes)" 4 00010203; }
@test "whole-file" { check_exact 0000000000000000 8 0000000000000000; }
@test "zero-count" { check_exact '' 0 ''; }
@test "across-ctrl-z" { check_exact 611a62 3 611a62; }

@test "one-past-end" {
  write 89504e470d0a1a0a0000000d49484452
  run -2 read_exact got "$file" 17
}

@test "empty-file" {
  write ''
  run -2 read_exact got "$file" 1
}

@test "missing" {
  run -1 read_bytes got "$BATS_TEST_TMPDIR/missing.bin"
  run -1 read_exact got "$BATS_TEST_TMPDIR/missing.bin" 1
}

@test "directory" {
  run -1 read_bytes got "$BATS_TEST_TMPDIR"
  run -1 read_exact got "$BATS_TEST_TMPDIR" 1
}

References

  1. The Python Standard Library, Built-in Functions, open(), the mode argument
  2. The Python Standard Library, io, Core tools for working with streams, BufferedIOBase.read, RawIOBase.read
  3. Node.js documentation, File system, fsPromises.readFile(path[, options]), filehandle.read(buffer, offset, length, position)
  4. Node.js documentation, Buffer, Buffers and character encodings, 'utf8'
  5. Java SE 25 API, java.nio.file.Files, readAllBytes(Path)
  6. Java SE 25 API, java.io.InputStream, read(byte[]), readNBytes(int)
  7. .NET API reference, File.ReadAllBytes
  8. .NET API reference, Stream.Read, Read(Byte[], Int32, Int32), Returns
  9. .NET API reference, Stream.ReadExactly, Exceptions
  10. Go standard library, package os, func ReadFile
  11. Go standard library, package io, func ReadFull
  12. The Rust Standard Library, std::fs::read
  13. The Rust Standard Library, std::io::Read, read_exact, Errors
  14. The Open Group, POSIX.1-2024, fopen, Description, the mode character b
  15. The Open Group, POSIX.1-2024, fread, Return value
  16. Microsoft C runtime library reference, fopen, _wfopen, the translation modes t and b
  17. cppreference, std::basic_istream::read
  18. The Open Group, POSIX.1-2024, od, Options, -A, -N, -t, -v
  19. PNG (Portable Network Graphics) Specification, Version 1.2, Rationale, 12.12 PNG file signature

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source