Taskcore
Embed a file in a program
Also called embed a resource, include a file at compile time, go:embed, include_str, include_bytes, #embed, embedded resource, package data, resource file, bundle a file.
Put the bytes of a data file into a program when it is built, so that the program reads them from memory at run time and does not depend on the working directory or on a file next to it.
- Evidence
- Code in 6 languages
Task
Put the text file lines.txt into the program when the program is built. Then return line n of it, with no line end, from the copy in memory. Line 1 is the first line after the license header. Return no value when n is less than 1 or more than the number of lines.
The file is next to the source of each solution, and it is UTF-8. Its first line is the license header # SPDX-License-Identifier: MIT, because each file of a solution on this site starts with one. The four lines after it are alpha, café, an empty line and gamma. Each line ends with \n, so the file has 50 bytes. Each solution skips the header line.
A program that opens lines.txt at run time does not do the task. Such a program fails when it starts in another directory, or when a person copies only the program to another computer. With an embedded file, the program is the only thing to install.
SQL, regular expressions, HTML and CSS do not apply, because they do not build programs.
Solutions
The compiled languages read the file in the build, and put its bytes in the program as a constant. The other languages do not have a build step that can do this, so they ship the file with the code and find it through the loader, not through the working directory.
- Go. A
//go:embeddirective above a variable at package scope. "Package embed provides access to files embedded in the running Go program."1 The directive can "initialize a variable of type string, []byte, or FS with the contents of files read from the package directory or subdirectories at compile time"1. For astring, "The //go:embed line for a variable of type string or []byte can have only a single pattern, and that pattern can match only a single file."1 Only "Go source files that import "embed" can use the //go:embed directive"1, so the code hasimport _ "embed", also though it uses only astring. - Rust.
include_str!("lines.txt")"Includes a UTF-8 encoded file as a string."3, andinclude_bytes!gives "an expression of type &'static [u8; N] which is the contents of the file"2. For each macro, "The file is located relative to the current file (similarly to how modules are found)."3 The code usesstr::lines, and returnsNonefornless than 1 before it convertsnto an index. - C. The
#embeddirective in an initializer: "#embed is a preprocessor directive to include (binary) resources in the build"4. It "replaces the directive by a comma separated list of integers corresponding to the data of the resource"4. A compiler with no#embeddoes not define__has_embed, so the code uses#if defined(__has_embed), and else includeslines_txt.h, the same list of bytes thatxxd -imade. The native test checks that the header agrees withlines.txt. The array has no 0 byte at its end, so the function returns a pointer and a length, not a C string. - C++. The same two forms. The code uses
#embedonly when__cplusplusis more than202302Land the compiler has__has_embed. Else it includeslines_txt.h, because#embedin an earlier mode is an extension, and a build with warnings as errors stops on it. The function returnsstd::optional<std::string_view>, a view into the array, so it does not copy the line. - Python. Python has no build step that puts a file into a program. The file ships next to the module, and
importlib.resourcesfinds it. "This module leverages Python’s import system to provide access to resources within packages ."6 The resources "may be contained directly in a package, within a subdirectory contained in that package, or adjacent to modules outside a package"6. Soresources.files(__name__)works for a module that is not in a package. The loader finds the file, so the working directory does not matter, and "a package and its resources can be imported from a zip file using zipimport"6. The code reads the file one time, and keeps the lines. - Bash. A script has no build step, so the text is in the script as a here-document. "The redirection operators "<<" and "<<-" both allow redirection of subsequent lines read by the shell to the input of a command."11 The delimiter is quoted (
<<'END_OF_LINES'), and "If any part of word is quoted, not counting double-quotes outside a command substitution if the here-document is inside one, the delimiter shall be formed by performing quote removal on word , and the here-document lines shall not be expanded."11 So a$or a backquote in the text stays as it is. The native test compares the text withlines.txt.
Java, C#, JavaScript and TypeScript have no solution here, because each one embeds a file through its build tool or packager, and the test harness of this site compiles only the source files:
- Java. A file in a JAR, next to the classes, is a resource.
Class.getResourceAsStream(name)"Finds a resource with a given name."7 A name with no/at the start is relative to the package of the class: "the absolute name is of the following form: modified_package_name/name"7. The method returns "null if no resource with this name is found"7, so check for null. - C#. An
EmbeddedResourceitem in the project file "Represents resources to be embedded in the generated assembly."9 At run time,Assembly.GetManifestResourceStream(name)"Loads the specified manifest resource from this assembly."8 It returns "null if no resources were specified during compilation or if the resource is not visible to the caller"8. The item has aLogicalName, "The logical name of the embedded resource."9, and the code must use that name. - JavaScript and TypeScript (Node.js). A module can read a file next to it at run time, with a path from the location of the module. To ship one file, a single executable application "allows the distribution of a Node.js application conveniently to a system that does not have Node.js installed"10, and
sea.getAsset(key)can "retrieve the assets configured to be bundled into the single-executable application at build time"10. A bundler can also put the text of a file into the code of a module.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
first-lineandlast-line: lines 1 and 4 arealphaandgamma. The text after the last\nis empty, and it is not a fifth line.non-ascii-line: line 2 iscafé, 5 bytes in UTF-8. The embedded data has the bytes of the file, not characters. Rust'sinclude_str!and Go'sstringkeep the UTF-8 bytes, and C and C++ get the values of the bytes.empty-line: line 3 is an empty string. That is a line, not the end of the data.zero,negativeandpast-the-end: lines 0, -1 and 5 do not exist, and the result is no value. In Rust, a negativenmust not become a largeusizeindex.
The native tests also check that the embedded bytes are the 50 bytes of lines.txt, and, in Python, Go, Rust and Bash, that the result does not change when the working directory changes. C and C++ also check that lines_txt.h has the same bytes as lines.txt.
Pitfalls
- A path from the working directory. A program that opens
lines.txtby a relative path looks in the working directory, not in the directory of the code. It works when a person starts it in the directory of the project, and fails in other places:
This code runs but gives a wrong answer on purpose.
import os
import tempfile
with tempfile.TemporaryDirectory() as project, tempfile.TemporaryDirectory() as other:
with open(os.path.join(project, "lines.txt"), "w", encoding="utf-8") as f:
f.write("alpha\n")
start = os.getcwd()
os.chdir(other) # the program starts in another directory
try:
with open("lines.txt", encoding="utf-8") as f:
print(f.readline())
except FileNotFoundError as e:
print("error:", e.strerror)
finally:
os.chdir(start)
error: No such file or directory
Embed the file, or find it through the loader. A path from __file__ works only while the module is a file on the disk. importlib.resources also works for a module in a zip file, where no file lines.txt exists:
import os
import sys
import tempfile
import zipfile
from importlib import resources
with tempfile.TemporaryDirectory() as d:
archive = os.path.join(d, "app.zip")
with zipfile.ZipFile(archive, "w") as z:
z.writestr("app/__init__.py", "")
z.writestr("app/lines.txt", "alpha\ncafé\n")
sys.path.insert(0, archive)
import app
print("loader:", type(app.__loader__).__name__)
text = resources.files("app").joinpath("lines.txt").read_text(encoding="utf-8")
print("lines:", text.splitlines())
print("a file on the disk:", os.path.exists(os.path.join(d, "app", "lines.txt")))
loader: zipimporter
lines: ['alpha', 'café']
a file on the disk: False
- A large file in source code. Before
#embed, C and C++ programs used a list of bytes in source code, and a tool such asxxdmade it. The author of#embedwrites that users reach "for utilities such as xxd , writing python scripts, or engaging in highly platform-specific linker calls to set up extern variables pointing at their data"5. Such a list is slow to compile. In the measurements of N3017, a file of 40 megabytes took 1.069 s with#embedin GCC, and 225.290 s as anxxdlist in GCC, 83.250 s in Clang, and "Out of Memory" in MSVC5. GCC used 341.72 MB of memory with#embed, and 12,622.00 MB for thexxdlist5. Keep the generated list for small files, or for a compiler with no#embed. - A copy that is old. The program has the bytes that the file had at build time. After a change of the file, build again. The build system must know that the program depends on the data file, or it does not build the program again.
- The rules of the directive. In Go, "It can only be used with variables at package scope, not with local variables."1 And when a pattern names a directory, "files with names beginning with ‘.’ or ‘_’ are excluded"1. "If any patterns are invalid or have invalid matches, the build will fail."1 In Rust, "an invocation with a Windows path containing backslashes \ would not compile correctly on Unix"3, so use
/in the path. - An empty or missing file in C.
#embedof an empty file gives no values, and an array of unknown size with no values is an error.__has_embed"evaluates to STDC_EMBED_FOUND if the search for the resource succeeds, the resource is non empty and all the parameters are supported"4, and theif_emptyparameter gives values for an empty file4. - A resource that is not there. In Java and .NET, a wrong name, or a file that the build did not include, gives null at run time, not an error at build time78. Check for null, and test the packaged program.
- The size of the program. Each embedded byte is in the program file, so a large file makes a large program. Embed small files, such as templates, schemas and test data. For large data, ship a file and find it from the path of the program.
Related tasks
- Read a whole file
- Read a file line by line
- Read a binary file
- Check whether a file exists
- Create a temporary file
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/embed-a-file-in-a-program/.
from functools import cache
from importlib import resources
@cache
def _lines() -> list[str]:
"""Reads lines.txt one time, from the place where this module is.
Python has no step that puts a file into the program. The file ships
next to the module, as package data, and importlib.resources finds it
through the import system, so the working directory does not matter and
a module in a zip file also works.
"""
text = resources.files(__name__).joinpath("lines.txt").read_text(encoding="utf-8")
# Line 0 is the license header of the file, and the text after the last
# "\n" is empty.
return text.split("\n")[1:-1]
def embedded_line(n: int) -> str | None:
"""Returns line n of lines.txt (1 is the line after the header), or None."""
lines = _lines()
return lines[n - 1] if 1 <= n <= len(lines) else None
lines.txt 5 lines
# SPDX-License-Identifier: MIT
alpha
café
gamma
test_embed_file.py 44 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/embed-a-file-in-a-program/.
import os
from importlib import resources
from pathlib import Path
import pytest
import embed_file
from embed_file import embedded_line
CASES = {
"first-line": (1, "alpha"),
"second-line": (2, "café"),
"last-line": (4, "gamma"),
"non-ascii-line": (2, "café"),
"empty-line": (3, ""),
"zero": (0, None),
"negative": (-1, None),
"past-the-end": (5, None),
}
@pytest.mark.parametrize("name", CASES)
def test_cases(name: str) -> None:
n, want = CASES[name]
assert embedded_line(n) == want
def test_bytes_are_the_file() -> None:
data = resources.files(embed_file.__name__).joinpath("lines.txt").read_bytes()
assert data == "# SPDX-License-Identifier: MIT\nalpha\ncafé\n\ngamma\n".encode()
assert len(data) == 50
def test_working_directory_does_not_matter(tmp_path: Path) -> None:
embed_file._lines.cache_clear()
old = os.getcwd()
os.chdir(tmp_path)
try:
assert embedded_line(4) == "gamma"
finally:
os.chdir(old)
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/embed-a-file-in-a-program/.
#include "embed_file.hpp"
namespace {
// #embed is part of the C++ draft after C++23. A compiler that has it in
// that mode uses it; the others use the same bytes from a header that a tool
// such as xxd made from lines.txt.
constexpr unsigned char data[] = {
#if __cplusplus > 202302L && defined(__has_embed)
#embed "lines.txt"
#else
#include "lines_txt.h"
#endif
};
} // namespace
namespace files {
std::span<const unsigned char> embedded_data() { return data; }
std::optional<std::string_view> embedded_line(std::int64_t n) {
std::string_view rest(reinterpret_cast<const char*>(data), sizeof data);
if (n < 1) {
return std::nullopt;
}
// Skip the first line, the license header of the file.
auto first = rest.find('\n');
if (first == std::string_view::npos) {
return std::nullopt;
}
rest.remove_prefix(first + 1);
for (std::int64_t i = 1; !rest.empty(); ++i) {
auto nl = rest.find('\n');
auto line = rest.substr(0, nl);
if (i == n) {
return line;
}
rest = nl == std::string_view::npos ? std::string_view{} : rest.substr(nl + 1);
}
return std::nullopt;
}
} // namespace files
embed_file.hpp 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/embed-a-file-in-a-program/.
#pragma once
#include <cstdint>
#include <optional>
#include <span>
#include <string_view>
namespace files {
// The bytes of lines.txt, put in the program when it is compiled.
std::span<const unsigned char> embedded_data();
// Returns line n of lines.txt (1 is the line after the license header),
// with no line end, or
// std::nullopt when there is no such line. The view points into the
// embedded data, so it stays valid for the whole run of the program.
std::optional<std::string_view> embedded_line(std::int64_t n);
} // namespace files
lines.txt 5 lines
# SPDX-License-Identifier: MIT
alpha
café
gamma
lines_txt.h 12 lines
/* SPDX-License-Identifier: MIT */
/* Part of https://programming.tamnd.com/embed-a-file-in-a-program/. */
/* The bytes of lines.txt as an initializer list, for a compiler that has no
#embed. Make the list again after a change of lines.txt, for example with
the output of xxd -i < lines.txt. The native test checks that the two
agree. */
0x23, 0x20, 0x53, 0x50, 0x44, 0x58, 0x2d, 0x4c, 0x69, 0x63, 0x65, 0x6e,
0x73, 0x65, 0x2d, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65,
0x72, 0x3a, 0x20, 0x4d, 0x49, 0x54, 0x0a, 0x61, 0x6c, 0x70, 0x68, 0x61,
0x0a, 0x63, 0x61, 0x66, 0xc3, 0xa9, 0x0a, 0x0a, 0x67, 0x61, 0x6d, 0x6d,
0x61, 0x0a,
test_embed_file.cpp 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/embed-a-file-in-a-program/.
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <optional>
#include <string_view>
#include "embed_file.hpp"
namespace {
int failures = 0;
void check(const char* name, std::int64_t n, std::optional<std::string_view> want) {
if (files::embedded_line(n) != want) {
std::fprintf(stderr, "FAIL %s: line %lld\n", name, static_cast<long long>(n));
++failures;
}
}
// The bytes of the header, to check them against lines.txt.
constexpr unsigned char header[] = {
#include "lines_txt.h"
};
} // namespace
int main() {
using namespace std::string_view_literals;
check("first-line", 1, "alpha"sv);
check("second-line", 2, "caf\xc3\xa9"sv);
check("last-line", 4, "gamma"sv);
check("non-ascii-line", 2, "caf\xc3\xa9"sv);
check("empty-line", 3, ""sv);
check("zero", 0, std::nullopt);
check("negative", -1, std::nullopt);
check("past-the-end", 5, std::nullopt);
auto data = files::embedded_data();
constexpr auto want = "# SPDX-License-Identifier: MIT\nalpha\ncaf\xc3\xa9\n\ngamma\n"sv;
if (data.size() != 50 || std::memcmp(data.data(), want.data(), want.size()) != 0) {
std::fprintf(stderr, "FAIL bytes: %zu bytes\n", data.size());
++failures;
}
if (sizeof header != data.size() || std::memcmp(header, data.data(), data.size()) != 0) {
std::fprintf(stderr, "FAIL header: lines_txt.h does not match the data\n");
++failures;
}
if (failures == 0) {
std::puts("ok");
}
return failures == 0 ? 0 : 1;
}
/* SPDX-License-Identifier: MIT */
/* Part of https://programming.tamnd.com/embed-a-file-in-a-program/. */
#include "embed_file.h"
#include <string.h>
/* The preprocessor reads lines.txt, relative to this source file, and puts
its bytes here as a list of integers. A compiler with no #embed does not
define __has_embed, so it uses the same list from a header. */
static const unsigned char data[] = {
#if defined(__has_embed)
#embed "lines.txt"
#else
#include "lines_txt.h"
#endif
};
const unsigned char *embedded_data(size_t *len) {
*len = sizeof data;
return data;
}
const char *embedded_line(long n, size_t *len) {
const char *p = (const char *)data;
const char *end = p + sizeof data;
if (n < 1) {
return NULL;
}
/* Skip the first line, the license header of the file. */
const char *header_end = memchr(p, '\n', sizeof data);
if (header_end == NULL) {
return NULL;
}
p = header_end + 1;
for (long i = 1; p < end; i++) {
const char *nl = memchr(p, '\n', (size_t)(end - p));
if (nl == NULL) {
nl = end; /* a last line with no "\n" */
}
if (i == n) {
*len = (size_t)(nl - p);
return p;
}
p = nl + 1;
}
return NULL;
}
embed_file.h 18 lines
/* SPDX-License-Identifier: MIT */
/* Part of https://programming.tamnd.com/embed-a-file-in-a-program/. */
#ifndef EMBED_FILE_H
#define EMBED_FILE_H
#include <stddef.h>
/* The bytes of lines.txt, put in the program when it is compiled. */
const unsigned char *embedded_data(size_t *len);
/* Returns a pointer to the start of line n of lines.txt (1 is the line after
the license header)
and sets *len to its length with no line end. The line is not followed by
a 0 byte. Returns NULL when there is no such line. */
const char *embedded_line(long n, size_t *len);
#endif
lines.txt 5 lines
# SPDX-License-Identifier: MIT
alpha
café
gamma
lines_txt.h 12 lines
/* SPDX-License-Identifier: MIT */
/* Part of https://programming.tamnd.com/embed-a-file-in-a-program/. */
/* The bytes of lines.txt as an initializer list, for a compiler that has no
#embed. Make the list again after a change of lines.txt, for example with
the output of xxd -i < lines.txt. The native test checks that the two
agree. */
0x23, 0x20, 0x53, 0x50, 0x44, 0x58, 0x2d, 0x4c, 0x69, 0x63, 0x65, 0x6e,
0x73, 0x65, 0x2d, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65,
0x72, 0x3a, 0x20, 0x4d, 0x49, 0x54, 0x0a, 0x61, 0x6c, 0x70, 0x68, 0x61,
0x0a, 0x63, 0x61, 0x66, 0xc3, 0xa9, 0x0a, 0x0a, 0x67, 0x61, 0x6d, 0x6d,
0x61, 0x0a,
test_embed_file.c 52 lines
/* SPDX-License-Identifier: MIT */
/* Part of https://programming.tamnd.com/embed-a-file-in-a-program/. */
#include "embed_file.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
static void check(const char *name, long n, const char *want) {
size_t len = 0;
const char *got = embedded_line(n, &len);
int ok = want == NULL ? got == NULL
: got != NULL && len == strlen(want) && memcmp(got, want, len) == 0;
if (!ok) {
printf("FAIL %s: line %ld\n", name, n);
failures++;
}
}
/* The fallback header must hold the same bytes as lines.txt. */
static const unsigned char header[] = {
#include "lines_txt.h"
};
int main(void) {
check("first-line", 1, "alpha");
check("second-line", 2, "caf\xc3\xa9");
check("last-line", 4, "gamma");
check("non-ascii-line", 2, "caf\xc3\xa9");
check("empty-line", 3, "");
check("zero", 0, NULL);
check("negative", -1, NULL);
check("past-the-end", 5, NULL);
size_t len = 0;
const unsigned char *data = embedded_data(&len);
const char *want = "# SPDX-License-Identifier: MIT\nalpha\ncaf\xc3\xa9\n\ngamma\n";
if (len != 50 || memcmp(data, want, len) != 0) {
printf("FAIL bytes: %zu bytes\n", len);
failures++;
}
if (sizeof header != len || memcmp(header, data, len) != 0) {
printf("FAIL header: lines_txt.h does not match lines.txt\n");
failures++;
}
if (failures == 0) {
printf("ok\n");
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/embed-a-file-in-a-program/.
// Package embedfile puts lines.txt into the program when it is built.
package embedfile
import (
_ "embed"
"strings"
)
// lines holds the bytes of lines.txt. The go command reads the file at
// build time; the program does not open it at run time.
//
//go:embed lines.txt
var lines string
// EmbeddedLine returns line n of lines.txt (1 is the line after the license
// header), with no line end. The bool is false when there is no such line.
func EmbeddedLine(n int) (string, bool) {
all := strings.Split(lines, "\n")
// all[0] is the license header, and the text after the last "\n" is empty.
all = all[1 : len(all)-1]
if n < 1 || n > len(all) {
return "", false
}
return all[n-1], true
}
lines.txt 5 lines
# SPDX-License-Identifier: MIT
alpha
café
gamma
embed_file_test.go 59 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/embed-a-file-in-a-program/.
package embedfile
import (
"os"
"testing"
)
func TestCases(t *testing.T) {
cases := []struct {
name string
n int
want string
ok bool
}{
{"first-line", 1, "alpha", true},
{"second-line", 2, "café", true},
{"last-line", 4, "gamma", true},
{"non-ascii-line", 2, "café", true},
{"empty-line", 3, "", true},
{"zero", 0, "", false},
{"negative", -1, "", false},
{"past-the-end", 5, "", false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, ok := EmbeddedLine(c.n)
if got != c.want || ok != c.ok {
t.Fatalf("EmbeddedLine(%d) = %q, %v; want %q, %v", c.n, got, ok, c.want, c.ok)
}
})
}
}
func TestBytesAreTheFile(t *testing.T) {
data, err := os.ReadFile("lines.txt")
if err != nil {
t.Fatal(err)
}
if lines != string(data) || len(lines) != 50 {
t.Fatalf("embedded %q (%d bytes), file %q", lines, len(lines), data)
}
}
func TestWorkingDirectoryDoesNotMatter(t *testing.T) {
old, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
if err := os.Chdir(t.TempDir()); err != nil {
t.Fatal(err)
}
defer os.Chdir(old)
if got, ok := EmbeddedLine(4); got != "gamma" || !ok {
t.Fatalf("got %q, %v", got, ok)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/embed-a-file-in-a-program/.
/// The text of lines.txt. The compiler reads the file, relative to this
/// source file, and puts it in the program as a `&'static str`.
pub const LINES: &str = include_str!("lines.txt");
/// The same file as bytes, a `&'static [u8; N]`.
pub const BYTES: &[u8] = include_bytes!("lines.txt");
/// Returns line `n` of lines.txt (1 is the line after the license header), with no line end, or
/// `None` when there is no such line.
pub fn embedded_line(n: i64) -> Option<String> {
if n < 1 {
return None;
}
let index = usize::try_from(n - 1).ok()?;
// The first line is the license header of the file.
LINES.lines().skip(1).nth(index).map(str::to_string)
}
lines.txt 5 lines
# SPDX-License-Identifier: MIT
alpha
café
gamma
tests/embed_file_test.rs 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/embed-a-file-in-a-program/.
use algo_embed_a_file_in_a_program::{embedded_line, BYTES, LINES};
#[test]
fn cases() {
let cases: [(&str, i64, Option<&str>); 8] = [
("first-line", 1, Some("alpha")),
("second-line", 2, Some("café")),
("last-line", 4, Some("gamma")),
("non-ascii-line", 2, Some("café")),
("empty-line", 3, Some("")),
("zero", 0, None),
("negative", -1, None),
("past-the-end", 5, None),
];
for (name, n, want) in cases {
assert_eq!(embedded_line(n).as_deref(), want, "{name}");
}
}
#[test]
fn bytes_are_the_file() {
assert_eq!(BYTES, "# SPDX-License-Identifier: MIT\nalpha\ncafé\n\ngamma\n".as_bytes());
assert_eq!(BYTES.len(), 50);
assert_eq!(LINES.as_bytes(), BYTES);
}
#[test]
fn working_directory_does_not_matter() {
let dir = std::env::temp_dir().join(format!("embed-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::env::set_current_dir(&dir).unwrap();
assert_eq!(embedded_line(4).as_deref(), Some("gamma"));
std::fs::remove_dir_all(&dir).unwrap();
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/embed-a-file-in-a-program/.
# A shell script has no build step, so the text of lines.txt is in the
# script itself, as a here-document. The quoted delimiter stops parameter
# expansion and command substitution in the text, so a $ or a ` in the file
# stays as it is.
embedded_text() {
cat <<'END_OF_LINES'
# SPDX-License-Identifier: MIT
alpha
café
gamma
END_OF_LINES
}
# embedded_line N
# Prints line N of the embedded text (1 is the line after the license
# header), with no line end.
# Returns status 1, and prints nothing, when there is no such line.
embedded_line() {
local n=$1 i=-1 line
[[ $n =~ ^-?[0-9]+$ ]] || return 1
((n >= 1)) || return 1
while IFS= read -r line; do
i=$((i + 1))
if ((i == n)); then
printf '%s' "$line"
return 0
fi
done < <(embedded_text)
return 1
}
lines.txt 5 lines
# SPDX-License-Identifier: MIT
alpha
café
gamma
test_embed_file.bats 56 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/embed-a-file-in-a-program/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/embed_file.sh"
}
@test "first-line" {
[ "$(embedded_line 1)" = alpha ]
}
@test "second-line" {
[ "$(embedded_line 2)" = "$(printf 'caf\303\251')" ]
}
@test "last-line" {
[ "$(embedded_line 4)" = gamma ]
}
@test "non-ascii-line" {
[ "$(embedded_line 2 | wc -c | tr -d ' ')" = 5 ]
}
@test "empty-line" {
run embedded_line 3
[ "$status" -eq 0 ]
[ "$output" = "" ]
}
@test "zero" {
run embedded_line 0
[ "$status" -eq 1 ]
[ "$output" = "" ]
}
@test "negative" {
run embedded_line -1
[ "$status" -eq 1 ]
}
@test "past-the-end" {
run embedded_line 5
[ "$status" -eq 1 ]
}
@test "the text is the bytes of lines.txt" {
cmp <(embedded_text) "$BATS_TEST_DIRNAME/lines.txt"
}
@test "the working directory does not matter" {
cd "$BATS_TEST_TMPDIR"
[ "$(embedded_line 4)" = gamma ]
}
References
- Go standard library, package embed, Overview, Directives, Strings and Bytes
- The Rust Standard Library, macro include_bytes, Description
- The Rust Standard Library, macro include_str, Description
- cppreference, Binary resource inclusion (C23), Syntax, Explanation, Parameters
- N3017: #embed - a scannable, tooling-friendly binary resource inclusion mechanism, 3.1 Motivation, 3.2.1 Speed, 3.2.2 Memory Size
- The Python Standard Library, importlib.resources, Package resource reading, opening and access, introduction, files
- Java SE 25 API, Class, getResourceAsStream(String)
- .NET API reference, Assembly.GetManifestResourceStream Method, GetManifestResourceStream(String), Returns
- MSBuild documentation, Common MSBuild project items, EmbeddedResource
- Node.js documentation, Single executable applications, introduction, sea.getAsset(key[, encoding])
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), Shell Command Language, 2.7.4 Here-Document
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 (go) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag EHSVGA Edit this page History Report an error Markdown