Taskintro
Append to a file
Also called append a line to a file, add text to the end of a file, append to a log file, O_APPEND.
Add one line to the end of a file in append mode, with one write call, so that many threads or processes can add lines to the same file and no line overwrites another.
- Evidence
- Code in 10 languages
Task
Add one line to the end of a file. If the file does not exist, make it.
The solution writes the UTF-8 bytes of the line and one \n after the old content, with nothing between them. It does not read the file, and it does not change the old content. If the old content does not end with \n, the new line joins the last old line.
Many writers can use the same file at the same time: threads of one program, or many programs that write to one log. So the solution opens the file in append mode, and it sends the line and its \n in one write call. In append mode, POSIX moves the file offset to the end of the file before each write, and "no intervening file modification operation shall occur between changing the file offset and the write operation". A line from another writer then cannot go over the line.
If the parent directory does not exist, or if the line holds \n or \r, the solution reports an error and writes nothing.
To replace all of a file, or to write it atomically, see Write a file. SQL, regular expressions, HTML and CSS do not apply, because none of them can open a file.
Solutions
Each solution opens the file in append mode with "create" on, makes one buffer that holds the line and \n, writes it once and closes the file.
- Python.
os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o666)and oneos.write.open(path, "a")also appends, but it writes through a buffer, so the code does not control the number of write calls. - JavaScript and TypeScript (Node.js).
fsPromises.open(path, "a")and onefilehandle.write(buffer). The flag"a"means "Open file for appending. The file is created if it does not exist." The code comparesbytesWrittenwith the length of the buffer. - Java.
FileChannel.open(path, CREATE, WRITE, APPEND)and onewrite. The code checks that the buffer has no bytes left.Files.writeString(path, text, CREATE, APPEND)is shorter, but withoutCREATEit fails on a new file. - C#. .NET has no option for
O_APPEND.FileMode.Append"seeks to the end of the file" when the file opens, and later writes go to that position. So the solution opens the file withFileShare.None, which makes a second open fail "until the file is closed", and it tries again after 1 ms while another writer holds the file. After 10 seconds it gives up and throws. - Go.
os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o666)and onef.Write. The code returns the error ofClosetoo. - Rust.
OpenOptions::new().append(true).create(true).open(path)and onewrite. The code does not usewrite_all, because it can split the data into more than one write. It reports an error ifwritewrote less. - C. POSIX
openwithO_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, then onewriteof a buffer that holds the line and'\n'. The code tries the write again afterEINTR, reports a short write asEIOand checksclose. - C++.
std::ofstream(path, std::ios::binary | std::ios::app), onewriteof astd::stringthat holds the line and'\n', thenclose. The flagappseeks "to the end of stream before each write". The code returnsstd::expected<void, AppendError>(C++23). - Bash.
printf '%s\n' "$line" >>"$path". The redirection>>opens the file for appending, andprintfsends the line and the newline together.
PowerShell Add-Content adds text to the end of a file, and it can make a new file.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl. The file argument gives the content of the file before the call, and null means that there is no file. The cases that must give an error are in cases/errors.jsonl.
new-fileandnew-file-empty-line: there is no file. The solution makes it.empty-line: the line is empty, so the solution adds only\n.empty-file: the file exists and has no bytes.no-final-newline: the old content isone. The result isonetwo\n, because the solution does not read the file.crlf-file: the old lines end with\r\n. The new line ends with\n, and the old content stays.whitespaceandnon-ascii: blanks, a tab and characters of 2, 3 and 4 bytes stay as they are.- Errors: a missing parent directory, and a line that holds
\nor\r.
The native tests also start 8 writers, threads or processes, that each add 250 lines to one file at the same time. Each of the 2000 lines must be in the file once and whole. A solution that seeks to the end and then writes fails this test. In one run on macOS, File.AppendAllText from 8 .NET threads kept 1631 of the 2000 lines.
Pitfalls
- Seek to the end, then write. A writer that moves to the end of the file once, and then writes, can write over the lines of another writer. The other writer adds bytes between the seek and the write:
This code runs but gives a wrong answer on purpose.
import os
import tempfile
path = os.path.join(tempfile.mkdtemp(), "log.txt")
open(path, "wb").close()
# Two writers that each go to the end of the file once, when they open it.
a = os.open(path, os.O_WRONLY)
b = os.open(path, os.O_WRONLY)
os.lseek(a, 0, os.SEEK_END)
os.lseek(b, 0, os.SEEK_END)
os.write(a, b"A1\n")
os.write(b, b"B1\n")
os.write(a, b"A2\n")
os.close(a)
os.close(b)
print(open(path).read(), end="")
B1
A2
The line A1 is lost. With O_APPEND, each write goes to the end of the file as it is at the time of the write:
import os
import tempfile
path = os.path.join(tempfile.mkdtemp(), "log.txt")
open(path, "wb").close()
# With O_APPEND, each write goes to the end of the file as it is then.
a = os.open(path, os.O_WRONLY | os.O_APPEND)
b = os.open(path, os.O_WRONLY | os.O_APPEND)
os.write(a, b"A1\n")
os.write(b, b"B1\n")
os.write(a, b"A2\n")
os.close(a)
os.close(b)
print(open(path).read(), end="")
A1
B1
A2
FileMode.Appendin .NET. The name says "append", but .NET does not open the file withO_APPEND. dotnet/runtime issue 53432 says that .NET mimics "the append by setting the file offset to the end of the file". Issue 76408, which asks for real appends, is open. So two .NET writers act as the two writers above:
This code runs but gives a wrong answer on purpose.
using System;
using System.IO;
using System.Text;
string path = Path.Combine(Directory.CreateTempSubdirectory().FullName, "log.txt");
File.WriteAllText(path, "");
using (var a = new FileStream(path, FileMode.Append, FileAccess.Write))
using (var b = new FileStream(path, FileMode.Append, FileAccess.Write))
{
a.Write(Encoding.UTF8.GetBytes("A1\n"));
a.Flush();
b.Write(Encoding.UTF8.GetBytes("B1\n"));
b.Flush();
a.Write(Encoding.UTF8.GetBytes("A2\n"));
a.Flush();
}
Console.Write(File.ReadAllText(path));
B1
A2
File.AppendAllText and new StreamWriter(path, append: true) open the file in the same way. Use a lock, as the C# solution does with FileShare.None.
- A line in more than one write. Append mode puts each write at the end, but two writes of one line can have a line of another writer between them. A buffered stream can split a long line, and Rust
write_allcallswriteagain after a short write. The Rust documentation says: "make sure that all data that belongs together is written in one operation". It also says that append mode "does not necessarily guarantee that data appended by different processes or threads does not interleave". So keep each line short, and write it in one call. - No final newline. If the last old line has no
\n, the new line joins it:
This code runs but gives a wrong answer on purpose.
file=$(mktemp)
printf 'one' >"$file"
printf '%s\n' two >>"$file"
cat -- "$file"
rm -f -- "$file"
onetwo
If the file can come from another program, check its last byte before the first append.
APPENDwithoutCREATEin Java.Files.writeString(path, text, StandardOpenOption.APPEND)throwsNoSuchFileExceptionif the file does not exist. With no options,Files.write"works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present". GiveCREATEandAPPENDtogether.- Append on NFS. The Linux manual says that
O_APPEND"may lead to corrupted files on NFS filesystems if more than one process appends data to a file at once", because the client must simulate the append. On a network file system, use a lock or one writer process. - Append and read on one handle. If a file is open to read and to append, the position for reading can move to the end of the file after each write. The Rust documentation says to save the position before the write and restore it before the next 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/append-to-a-file/.
import os
def append_line(path: str | os.PathLike[str], line: str) -> None:
"""Add line and one "\\n" to the end of the file, in one write call."""
if "\n" in line or "\r" in line:
raise ValueError("the line must not hold \\n or \\r")
data = (line + "\n").encode("utf-8")
# O_APPEND moves the offset to the end of the file before each write.
# open(path, "a") also uses it, but its buffer can split a long line.
fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o666)
try:
written = os.write(fd, data)
finally:
os.close(fd)
if written != len(data):
raise OSError(f"short write: {written} of {len(data)} bytes")
test_append_line.py 63 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/append-to-a-file/.
import threading
from collections import Counter
from pathlib import Path
import pytest
from append_line import append_line
# name: (old content or None, line, content after)
CASES = {
"new-file": (None, "first", "first\n"),
"append-existing": ("one\n", "two", "one\ntwo\n"),
"new-file-empty-line": (None, "", "\n"),
"empty-line": ("a\n", "", "a\n\n"),
"empty-file": ("", "x", "x\n"),
"no-final-newline": ("one", "two", "onetwo\n"),
"crlf-file": ("one\r\n", "two", "one\r\ntwo\n"),
"whitespace": ("", " two spaces\ttab ", " two spaces\ttab \n"),
"non-ascii": ("naïve\n", "café 日本語 🙂", "naïve\ncafé 日本語 🙂\n"),
}
@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
old, line, want = CASES[name]
path = tmp_path / "log.txt"
if old is not None:
path.write_bytes(old.encode())
append_line(path, line)
assert path.read_bytes() == want.encode()
def test_missing_dir(tmp_path: Path) -> None:
with pytest.raises(FileNotFoundError):
append_line(tmp_path / "missing" / "log.txt", "x")
@pytest.mark.parametrize("line", ["a\nb", "a\rb"])
def test_invalid_line(tmp_path: Path, line: str) -> None:
path = tmp_path / "log.txt"
with pytest.raises(ValueError):
append_line(path, line)
assert not path.exists()
def test_many_writers(tmp_path: Path) -> None:
path = tmp_path / "log.txt"
writers, lines = 8, 250
def write(w: int) -> None:
for i in range(lines):
append_line(path, f"writer {w} line {i:03d} " + "x" * 40)
threads = [threading.Thread(target=write, args=(w,)) for w in range(writers)]
for t in threads:
t.start()
for t in threads:
t.join()
want = Counter(f"writer {w} line {i:03d} " + "x" * 40 for w in range(writers) for i in range(lines))
assert Counter(path.read_text(encoding="utf-8").splitlines()) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
// since: C++23 (std::expected)
#include "append_line.hpp"
#include <fstream>
#include <string>
std::expected<void, AppendError> append_line(const std::filesystem::path& path,
std::string_view line) {
if (line.find_first_of("\r\n") != std::string_view::npos) {
return std::unexpected(AppendError::invalid_line);
}
// std::ios::app seeks to the end before each write. Make the line and its
// '\n' one string and write it once, so that the stream sends it in one
// write call when it flushes.
std::string data{line};
data += '\n';
std::ofstream out(path, std::ios::binary | std::ios::app);
if (!out) return std::unexpected(AppendError::cannot_open);
out.write(data.data(), static_cast<std::streamsize>(data.size()));
out.close(); // flushes; close sets failbit if the flush fails
if (!out) return std::unexpected(AppendError::write_failed);
return {};
}
append_line.hpp 16 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
// since: C++23 (std::expected)
#pragma once
#include <expected>
#include <filesystem>
#include <string_view>
enum class AppendError { invalid_line, cannot_open, write_failed };
// Adds line and one '\n' to the end of the file at path, and makes the file
// if it is missing.
std::expected<void, AppendError> append_line(const std::filesystem::path& path,
std::string_view line);
test_append_line.cpp 100 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <format>
#include <fstream>
#include <optional>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include "append_line.hpp"
namespace {
const std::filesystem::path log_path = "append_line_log.txt";
std::string read_file() {
std::ifstream in(log_path, std::ios::binary);
std::ostringstream s;
s << in.rdbuf();
return s.str();
}
int failures = 0;
void check(const std::string& name, bool ok) {
if (!ok) {
std::fprintf(stderr, "case %s failed\n", name.c_str());
++failures;
}
}
std::string text(int w, int i) {
return std::format("writer {} line {:03} ", w, i) + std::string(40, 'x');
}
} // namespace
int main() {
struct Case {
std::string name;
std::optional<std::string> old; // nothing when no file is there
std::string line, want;
};
const std::vector<Case> cases = {
{"new-file", std::nullopt, "first", "first\n"},
{"append-existing", "one\n", "two", "one\ntwo\n"},
{"new-file-empty-line", std::nullopt, "", "\n"},
{"empty-line", "a\n", "", "a\n\n"},
{"empty-file", "", "x", "x\n"},
{"no-final-newline", "one", "two", "onetwo\n"},
{"crlf-file", "one\r\n", "two", "one\r\ntwo\n"},
{"whitespace", "", " two spaces\ttab ", " two spaces\ttab \n"},
{"non-ascii", "naïve\n", "café 日本語 🙂", "naïve\ncafé 日本語 🙂\n"},
};
for (const auto& c : cases) {
std::filesystem::remove(log_path);
if (c.old) std::ofstream(log_path, std::ios::binary) << *c.old;
check(c.name, append_line(log_path, c.line).has_value() && read_file() == c.want);
}
std::filesystem::remove(log_path);
check("missing-dir", append_line("missing_dir/log.txt", "x").error_or(AppendError::write_failed) ==
AppendError::cannot_open);
for (std::string line : {"a\nb", "a\rb"}) {
check("invalid-line", append_line(log_path, line).error_or(AppendError::write_failed) ==
AppendError::invalid_line &&
!std::filesystem::exists(log_path));
}
const int writers = 8, lines = 250;
std::vector<std::thread> threads;
std::vector<int> errors(writers, 0);
for (int w = 0; w < writers; ++w) {
threads.emplace_back([w, &errors] {
for (int i = 0; i < lines; ++i) {
if (!append_line(log_path, text(w, i))) ++errors[w];
}
});
}
for (auto& t : threads) t.join();
std::vector<std::string> got, want;
std::istringstream in(read_file());
for (std::string s; std::getline(in, s);) got.push_back(s);
for (int w = 0; w < writers; ++w) {
for (int i = 0; i < lines; ++i) want.push_back(text(w, i));
}
std::ranges::sort(got);
std::ranges::sort(want);
check("many-writers", got == want && std::ranges::count(errors, 0) == writers);
std::filesystem::remove(log_path);
if (failures != 0) return EXIT_FAILURE;
std::puts("all tests passed");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
/** Adds lines to the end of a file. */
public final class AppendLine {
private AppendLine() {}
/** Adds line and one "\n" to the end of the file, in one write call. */
public static void appendLine(Path path, String line) throws IOException {
if (line.indexOf('\n') >= 0 || line.indexOf('\r') >= 0) {
throw new IllegalArgumentException("the line must not hold \\n or \\r");
}
ByteBuffer data = ByteBuffer.wrap((line + "\n").getBytes(StandardCharsets.UTF_8));
// APPEND moves the position to the end of the file before each write.
try (FileChannel channel =
FileChannel.open(
path, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND)) {
channel.write(data);
}
if (data.hasRemaining()) {
throw new IOException("short write: " + data.remaining() + " bytes not written");
}
}
}
AppendLineTest.java 97 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
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;
import org.junit.jupiter.params.provider.ValueSource;
class AppendLineTest {
@TempDir Path dir;
// name, old content or null, line, content after
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("new-file", null, "first", "first\n"),
Arguments.of("append-existing", "one\n", "two", "one\ntwo\n"),
Arguments.of("new-file-empty-line", null, "", "\n"),
Arguments.of("empty-line", "a\n", "", "a\n\n"),
Arguments.of("empty-file", "", "x", "x\n"),
Arguments.of("no-final-newline", "one", "two", "onetwo\n"),
Arguments.of("crlf-file", "one\r\n", "two", "one\r\ntwo\n"),
Arguments.of("whitespace", "", " two spaces\ttab ", " two spaces\ttab \n"),
Arguments.of("non-ascii", "naïve\n", "café 日本語 🙂", "naïve\ncafé 日本語 🙂\n"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void appends(String name, String old, String line, String want) throws IOException {
Path path = dir.resolve("log.txt");
if (old != null) Files.writeString(path, old);
AppendLine.appendLine(path, line);
assertEquals(want, new String(Files.readAllBytes(path), StandardCharsets.UTF_8));
}
@Test
void missingDirectory() {
assertThrows(
NoSuchFileException.class,
() -> AppendLine.appendLine(dir.resolve("missing").resolve("log.txt"), "x"));
}
@ParameterizedTest
@ValueSource(strings = {"a\nb", "a\rb"})
void invalidLine(String line) {
Path path = dir.resolve("log.txt");
assertThrows(IllegalArgumentException.class, () -> AppendLine.appendLine(path, line));
assertFalse(Files.exists(path));
}
private static String text(int w, int i) {
return String.format("writer %d line %03d ", w, i) + "x".repeat(40);
}
@Test
void manyWriters() throws Exception {
Path path = dir.resolve("log.txt");
int writers = 8, lines = 250;
List<Thread> threads = new ArrayList<>();
List<Throwable> errors = Collections.synchronizedList(new ArrayList<>());
for (int w = 0; w < writers; w++) {
int id = w;
threads.add(
Thread.ofPlatform()
.start(
() -> {
try {
for (int i = 0; i < lines; i++) AppendLine.appendLine(path, text(id, i));
} catch (Throwable e) {
errors.add(e);
}
}));
}
for (Thread t : threads) t.join();
assertEquals(List.of(), errors);
List<String> want = new ArrayList<>();
for (int w = 0; w < writers; w++) for (int i = 0; i < lines; i++) want.add(text(w, i));
List<String> got = new ArrayList<>(Files.readAllLines(path));
Collections.sort(want);
Collections.sort(got);
assertEquals(want, got);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
// open, write and O_CLOEXEC are in POSIX.1-2008, not in ISO C.
#define _POSIX_C_SOURCE 200809L
#include "append_line.h"
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int append_line(const char *path, const char *line) {
size_t n = strlen(line);
if (strpbrk(line, "\r\n") != NULL) {
errno = EINVAL;
return -1;
}
// Put the line and its '\n' in one buffer, so that one write sends both.
char *data = malloc(n + 1);
if (data == NULL) return -1;
memcpy(data, line, n);
data[n] = '\n';
// O_APPEND moves the offset to the end of the file before each write.
int fd = open(path, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0666);
if (fd < 0) {
free(data);
return -1;
}
ssize_t written;
do {
written = write(fd, data, n + 1);
} while (written < 0 && errno == EINTR);
int err = written < 0 ? errno : (size_t)written != n + 1 ? EIO : 0;
free(data);
if (close(fd) != 0 && err == 0) err = errno;
if (err != 0) {
errno = err;
return -1;
}
return 0;
}
append_line.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
#ifndef APPEND_LINE_H
#define APPEND_LINE_H
// append_line adds line and one '\n' to the end of the file at path, in one
// write call, and makes the file if it is missing. It returns 0. On an error
// it returns -1 and sets errno: EINVAL if line holds '\n' or '\r', EIO for a
// short write, or the error of open, write or close.
int append_line(const char *path, const char *line);
#endif
test_append_line.c 139 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
// fork and waitpid are in POSIX.1-2008, not in ISO C.
#define _POSIX_C_SOURCE 200809L
#include "append_line.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
static const char *path = "append_line_log.txt";
static void write_file(const char *data) {
FILE *f = fopen(path, "wb");
assert(f != NULL);
assert(fputs(data, f) >= 0);
assert(fclose(f) == 0);
}
static char *read_file(size_t *len) {
FILE *f = fopen(path, "rb");
assert(f != NULL);
size_t cap = 1 << 20, n;
char *buf = malloc(cap);
assert(buf != NULL);
n = fread(buf, 1, cap - 1, f);
assert(!ferror(f) && n < cap - 1);
buf[n] = '\0';
fclose(f);
*len = n;
return buf;
}
// old is NULL when no file is there.
static void check(const char *name, const char *old, const char *line, const char *want) {
remove(path);
if (old != NULL) write_file(old);
size_t len;
if (append_line(path, line) != 0) {
fprintf(stderr, "case %s: error %d\n", name, errno);
exit(1);
}
char *got = read_file(&len);
if (len != strlen(want) || memcmp(got, want, len) != 0) {
fprintf(stderr, "case %s: wrong content\n", name);
exit(1);
}
free(got);
}
static void check_error(const char *name, const char *file, const char *line, int want) {
remove(path);
errno = 0;
if (append_line(file, line) != -1 || errno != want) {
fprintf(stderr, "case %s: want errno %d, got %d\n", name, want, errno);
exit(1);
}
if (access(path, F_OK) == 0) {
fprintf(stderr, "case %s: the file was made\n", name);
exit(1);
}
}
enum { WRITERS = 8, LINES = 250 };
static void text(char *buf, size_t size, int w, int i) {
snprintf(buf, size, "writer %d line %03d xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", w, i);
}
// Each writer is a separate process, as with many programs that share a log.
static void many_writers(void) {
remove(path);
char buf[128];
for (int w = 0; w < WRITERS; w++) {
pid_t pid = fork();
assert(pid >= 0);
if (pid == 0) {
for (int i = 0; i < LINES; i++) {
text(buf, sizeof buf, w, i);
if (append_line(path, buf) != 0) _exit(1);
}
_exit(0);
}
}
for (int w = 0; w < WRITERS; w++) {
int status;
assert(wait(&status) > 0);
assert(WIFEXITED(status) && WEXITSTATUS(status) == 0);
}
size_t len;
char *got = read_file(&len);
static int seen[WRITERS][LINES];
int count = 0;
for (char *s = strtok(got, "\n"); s != NULL; s = strtok(NULL, "\n"), count++) {
int w, i;
if (sscanf(s, "writer %d line %d", &w, &i) != 2 || w < 0 || w >= WRITERS || i < 0 ||
i >= LINES) {
fprintf(stderr, "many writers: bad line\n");
exit(1);
}
text(buf, sizeof buf, w, i);
if (strcmp(s, buf) != 0 || seen[w][i]++ != 0) {
fprintf(stderr, "many writers: line %d %d is wrong or twice\n", w, i);
exit(1);
}
}
if (count != WRITERS * LINES) {
fprintf(stderr, "many writers: %d lines\n", count);
exit(1);
}
free(got);
remove(path);
}
int main(void) {
check("new-file", NULL, "first", "first\n");
check("append-existing", "one\n", "two", "one\ntwo\n");
check("new-file-empty-line", NULL, "", "\n");
check("empty-line", "a\n", "", "a\n\n");
check("empty-file", "", "x", "x\n");
check("no-final-newline", "one", "two", "onetwo\n");
check("crlf-file", "one\r\n", "two", "one\r\ntwo\n");
check("whitespace", "", " two spaces\ttab ", " two spaces\ttab \n");
check("non-ascii", "na\xc3\xafve\n", "caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e \xf0\x9f\x99\x82",
"na\xc3\xafve\ncaf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e \xf0\x9f\x99\x82\n");
check_error("missing-dir", "missing_dir/log.txt", "x", ENOENT);
check_error("newline-in-line", path, "a\nb", EINVAL);
check_error("cr-in-line", path, "a\rb", EINVAL);
many_writers();
remove(path);
puts("all tests passed");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
using System.Diagnostics;
using System.Text;
public static class AppendLine
{
private static readonly UTF8Encoding Utf8 = new(false, true);
/// <summary>Adds line and one "\n" to the end of the file, in one write call.</summary>
/// <remarks>
/// FileMode.Append moves to the end of the file only when the file opens, and .NET has
/// no option for O_APPEND. So each write holds the file with FileShare.None, and a
/// second writer waits until the first closes the file.
/// </remarks>
public static void Append(string path, string line)
{
if (line.Contains('\n') || line.Contains('\r'))
{
throw new ArgumentException("the line must not hold \\n or \\r", nameof(line));
}
byte[] data = Utf8.GetBytes(line + "\n");
var clock = Stopwatch.StartNew();
while (true)
{
try
{
using var file = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.None);
file.Write(data);
return;
}
// Only the exact type IOException tells that another writer holds the file.
// DirectoryNotFoundException and the other subclasses go to the caller.
catch (IOException e) when (e.GetType() == typeof(IOException) && clock.Elapsed.TotalSeconds < 10)
{
Thread.Sleep(1);
}
}
}
}
AppendLineTests.cs 67 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
using System.Text;
using Xunit;
public sealed class AppendLineTests : IDisposable
{
private readonly string dir = Directory.CreateTempSubdirectory("append-line-").FullName;
public void Dispose() => Directory.Delete(dir, recursive: true);
// name, old content or null, line, content after
public static TheoryData<string, string?, string, string> Cases => new()
{
{ "new-file", null, "first", "first\n" },
{ "append-existing", "one\n", "two", "one\ntwo\n" },
{ "new-file-empty-line", null, "", "\n" },
{ "empty-line", "a\n", "", "a\n\n" },
{ "empty-file", "", "x", "x\n" },
{ "no-final-newline", "one", "two", "onetwo\n" },
{ "crlf-file", "one\r\n", "two", "one\r\ntwo\n" },
{ "whitespace", "", " two spaces\ttab ", " two spaces\ttab \n" },
{ "non-ascii", "naïve\n", "café 日本語 🙂", "naïve\ncafé 日本語 🙂\n" },
};
[Theory]
[MemberData(nameof(Cases))]
public void Appends(string name, string? old, string line, string want)
{
string path = Path.Combine(dir, "log.txt");
if (old != null) File.WriteAllBytes(path, Encoding.UTF8.GetBytes(old));
AppendLine.Append(path, line);
Assert.Equal(want, Encoding.UTF8.GetString(File.ReadAllBytes(path)));
Assert.False(string.IsNullOrEmpty(name));
}
[Fact]
public void MissingDirectory() =>
Assert.Throws<DirectoryNotFoundException>(() => AppendLine.Append(Path.Combine(dir, "missing", "log.txt"), "x"));
[Theory]
[InlineData("a\nb")]
[InlineData("a\rb")]
public void InvalidLine(string line)
{
string path = Path.Combine(dir, "log.txt");
Assert.Throws<ArgumentException>(() => AppendLine.Append(path, line));
Assert.False(File.Exists(path));
}
private static string Text(int w, int i) => $"writer {w} line {i:D3} " + new string('x', 40);
[Fact]
public void ManyWriters()
{
string path = Path.Combine(dir, "log.txt");
const int writers = 8, lines = 250;
var threads = Enumerable.Range(0, writers)
.Select(w => new Thread(() => { for (int i = 0; i < lines; i++) AppendLine.Append(path, Text(w, i)); }))
.ToList();
threads.ForEach(t => t.Start());
threads.ForEach(t => t.Join());
var want = Enumerable.Range(0, writers).SelectMany(w => Enumerable.Range(0, lines).Select(i => Text(w, i))).Order();
Assert.Equal(want, File.ReadAllLines(path).Order());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
import { open } from "node:fs/promises";
/** Add line and one "\n" to the end of the file, in one write call. */
export async function appendLine(path, line) {
if (/[\r\n]/.test(line)) throw new RangeError("the line must not hold \\n or \\r");
const data = Buffer.from(line + "\n", "utf8");
// The flag "a" opens the file with O_APPEND and makes it if it is missing.
// fsPromises.appendFile can call write more than once for one string.
const file = await open(path, "a");
try {
const { bytesWritten } = await file.write(data);
if (bytesWritten !== data.length) {
throw new Error(`short write: ${bytesWritten} of ${data.length} bytes`);
}
} finally {
await file.close();
}
}
appendLine.test.js 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
import { test } from "node:test";
import assert from "node:assert/strict";
import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { appendLine } from "./appendLine.js";
// name: [old content or null, line, content after]
const cases = {
"new-file": [null, "first", "first\n"],
"append-existing": ["one\n", "two", "one\ntwo\n"],
"new-file-empty-line": [null, "", "\n"],
"empty-line": ["a\n", "", "a\n\n"],
"empty-file": ["", "x", "x\n"],
"no-final-newline": ["one", "two", "onetwo\n"],
"crlf-file": ["one\r\n", "two", "one\r\ntwo\n"],
whitespace: ["", " two spaces\ttab ", " two spaces\ttab \n"],
"non-ascii": ["naïve\n", "café 日本語 🙂", "naïve\ncafé 日本語 🙂\n"],
};
async function withDir(body) {
const dir = await mkdtemp(join(tmpdir(), "append-line-"));
try {
await body(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
for (const [name, [old, line, want]] of Object.entries(cases)) {
test(name, () =>
withDir(async (dir) => {
const path = join(dir, "log.txt");
if (old !== null) await writeFile(path, old, "utf8");
await appendLine(path, line);
assert.equal(await readFile(path, "utf8"), want);
}));
}
test("missing directory", () =>
withDir(async (dir) => {
await assert.rejects(appendLine(join(dir, "missing", "log.txt"), "x"), { code: "ENOENT" });
}));
for (const line of ["a\nb", "a\rb"]) {
test(`invalid line ${JSON.stringify(line)}`, () =>
withDir(async (dir) => {
const path = join(dir, "log.txt");
await assert.rejects(appendLine(path, line), RangeError);
await assert.rejects(access(path), { code: "ENOENT" });
}));
}
test("many writers", () =>
withDir(async (dir) => {
const path = join(dir, "log.txt");
const writers = 8;
const lines = 250;
const text = (w, i) => `writer ${w} line ${String(i).padStart(3, "0")} ` + "x".repeat(40);
await Promise.all(
Array.from({ length: writers }, async (_, w) => {
for (let i = 0; i < lines; i++) await appendLine(path, text(w, i));
}),
);
const got = (await readFile(path, "utf8")).split("\n");
assert.equal(got.pop(), "");
const want = [];
for (let w = 0; w < writers; w++) for (let i = 0; i < lines; i++) want.push(text(w, i));
assert.deepEqual(got.sort(), want.sort());
}));
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
import { open } from "node:fs/promises";
/** Add line and one "\n" to the end of the file, in one write call. */
export async function appendLine(path: string, line: string): Promise<void> {
if (/[\r\n]/.test(line)) throw new RangeError("the line must not hold \\n or \\r");
const data = Buffer.from(line + "\n", "utf8");
// The flag "a" opens the file with O_APPEND and makes it if it is missing.
// fsPromises.appendFile can call write more than once for one string.
const file = await open(path, "a");
try {
const { bytesWritten } = await file.write(data);
if (bytesWritten !== data.length) {
throw new Error(`short write: ${bytesWritten} of ${data.length} bytes`);
}
} finally {
await file.close();
}
}
appendLine.test.ts 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
import { test } from "node:test";
import assert from "node:assert/strict";
import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { appendLine } from "./appendLine.ts";
// name: [old content or null, line, content after]
const cases: Record<string, [string | null, string, string]> = {
"new-file": [null, "first", "first\n"],
"append-existing": ["one\n", "two", "one\ntwo\n"],
"new-file-empty-line": [null, "", "\n"],
"empty-line": ["a\n", "", "a\n\n"],
"empty-file": ["", "x", "x\n"],
"no-final-newline": ["one", "two", "onetwo\n"],
"crlf-file": ["one\r\n", "two", "one\r\ntwo\n"],
whitespace: ["", " two spaces\ttab ", " two spaces\ttab \n"],
"non-ascii": ["naïve\n", "café 日本語 🙂", "naïve\ncafé 日本語 🙂\n"],
};
async function withDir(body: (dir: string) => Promise<void>): Promise<void> {
const dir = await mkdtemp(join(tmpdir(), "append-line-"));
try {
await body(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
for (const [name, [old, line, want]] of Object.entries(cases)) {
test(name, () =>
withDir(async (dir) => {
const path = join(dir, "log.txt");
if (old !== null) await writeFile(path, old, "utf8");
await appendLine(path, line);
assert.equal(await readFile(path, "utf8"), want);
}));
}
test("missing directory", () =>
withDir(async (dir) => {
await assert.rejects(appendLine(join(dir, "missing", "log.txt"), "x"), { code: "ENOENT" });
}));
for (const line of ["a\nb", "a\rb"]) {
test(`invalid line ${JSON.stringify(line)}`, () =>
withDir(async (dir) => {
const path = join(dir, "log.txt");
await assert.rejects(appendLine(path, line), RangeError);
await assert.rejects(access(path), { code: "ENOENT" });
}));
}
test("many writers", () =>
withDir(async (dir) => {
const path = join(dir, "log.txt");
const writers = 8;
const lines = 250;
const text = (w: number, i: number) => `writer ${w} line ${String(i).padStart(3, "0")} ` + "x".repeat(40);
await Promise.all(
Array.from({ length: writers }, async (_, w) => {
for (let i = 0; i < lines; i++) await appendLine(path, text(w, i));
}),
);
const got = (await readFile(path, "utf8")).split("\n");
assert.equal(got.pop(), "");
const want: string[] = [];
for (let w = 0; w < writers; w++) for (let i = 0; i < lines; i++) want.push(text(w, i));
assert.deepEqual(got.sort(), want.sort());
}));
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
// Package appendline adds lines to the end of a file.
package appendline
import (
"errors"
"os"
"strings"
)
// ErrInvalidLine reports a line that holds "\n" or "\r".
var ErrInvalidLine = errors.New("the line must not hold \\n or \\r")
// AppendLine adds line and one "\n" to the end of the file, in one write call.
func AppendLine(path, line string) error {
if strings.ContainsAny(line, "\r\n") {
return ErrInvalidLine
}
// O_APPEND moves the offset to the end of the file before each write.
f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o666)
if err != nil {
return err
}
_, werr := f.Write([]byte(line + "\n"))
cerr := f.Close()
if werr != nil {
return werr
}
return cerr
}
append_line_test.go 118 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
package appendline
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
)
type appendCase struct {
old *string // nil when no file is there
line, want string
}
func ptr(s string) *string { return &s }
var cases = map[string]appendCase{
"new-file": {nil, "first", "first\n"},
"append-existing": {ptr("one\n"), "two", "one\ntwo\n"},
"new-file-empty-line": {nil, "", "\n"},
"empty-line": {ptr("a\n"), "", "a\n\n"},
"empty-file": {ptr(""), "x", "x\n"},
"no-final-newline": {ptr("one"), "two", "onetwo\n"},
"crlf-file": {ptr("one\r\n"), "two", "one\r\ntwo\n"},
"whitespace": {ptr(""), " two spaces\ttab ", " two spaces\ttab \n"},
"non-ascii": {ptr("naïve\n"), "café 日本語 🙂", "naïve\ncafé 日本語 🙂\n"},
}
func TestCases(t *testing.T) {
for name, c := range cases {
t.Run(name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "log.txt")
if c.old != nil {
if err := os.WriteFile(path, []byte(*c.old), 0o644); err != nil {
t.Fatal(err)
}
}
if err := AppendLine(path, c.line); err != nil {
t.Fatal(err)
}
got, err := os.ReadFile(path)
if err != nil || string(got) != c.want {
t.Fatalf("file = %q, %v; want %q", got, err, c.want)
}
})
}
}
func TestMissingDir(t *testing.T) {
err := AppendLine(filepath.Join(t.TempDir(), "missing", "log.txt"), "x")
if !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("err = %v; want fs.ErrNotExist", err)
}
}
func TestInvalidLine(t *testing.T) {
for _, line := range []string{"a\nb", "a\rb"} {
path := filepath.Join(t.TempDir(), "log.txt")
if err := AppendLine(path, line); !errors.Is(err, ErrInvalidLine) {
t.Fatalf("AppendLine(%q) = %v; want ErrInvalidLine", line, err)
}
if _, err := os.Stat(path); !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("the file was made for %q", line)
}
}
}
func text(w, i int) string {
return fmt.Sprintf("writer %d line %03d ", w, i) + strings.Repeat("x", 40)
}
func TestManyWriters(t *testing.T) {
path := filepath.Join(t.TempDir(), "log.txt")
const writers, lines = 8, 250
var wg sync.WaitGroup
errs := make(chan error, writers)
for w := range writers {
wg.Add(1)
go func() {
defer wg.Done()
for i := range lines {
if err := AppendLine(path, text(w, i)); err != nil {
errs <- err
return
}
}
}()
}
wg.Wait()
close(errs)
for err := range errs {
t.Fatal(err)
}
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
got := strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")
var want []string
for w := range writers {
for i := range lines {
want = append(want, text(w, i))
}
}
slices.Sort(got)
slices.Sort(want)
if !slices.Equal(got, want) {
t.Fatalf("got %d lines; want the %d lines of the writers", len(got), len(want))
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
use std::fs::OpenOptions;
use std::io::{self, ErrorKind, Write};
use std::path::Path;
/// Adds `line` and one `\n` to the end of the file, in one write call.
///
/// Append mode puts each write at the end of the file, but `write_all`
/// can split the data into more than one write. So the code calls `write`
/// once and reports an error if it wrote less.
pub fn append_line(path: impl AsRef<Path>, line: &str) -> io::Result<()> {
if line.contains(['\n', '\r']) {
return Err(io::Error::new(ErrorKind::InvalidInput, "the line must not hold \\n or \\r"));
}
let data = format!("{line}\n");
let mut file = OpenOptions::new().append(true).create(true).open(path)?;
let written = file.write(data.as_bytes())?;
if written != data.len() {
return Err(io::Error::other(format!("short write: {written} of {} bytes", data.len())));
}
Ok(())
}
tests/append_line_test.rs 85 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-file/.
use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::thread;
use algo_append_to_a_file::append_line;
/// Returns a new empty directory for one test.
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("append-line-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn cases() {
// name, old content or None, line, content after
let cases: [(&str, Option<&str>, &str, &str); 9] = [
("new-file", None, "first", "first\n"),
("append-existing", Some("one\n"), "two", "one\ntwo\n"),
("new-file-empty-line", None, "", "\n"),
("empty-line", Some("a\n"), "", "a\n\n"),
("empty-file", Some(""), "x", "x\n"),
("no-final-newline", Some("one"), "two", "onetwo\n"),
("crlf-file", Some("one\r\n"), "two", "one\r\ntwo\n"),
("whitespace", Some(""), " two spaces\ttab ", " two spaces\ttab \n"),
("non-ascii", Some("naïve\n"), "café 日本語 🙂", "naïve\ncafé 日本語 🙂\n"),
];
for (name, old, line, want) in cases {
let path = temp_dir(name).join("log.txt");
if let Some(old) = old {
fs::write(&path, old).unwrap();
}
append_line(&path, line).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), want, "{name}");
}
}
#[test]
fn missing_dir() {
let err = append_line(temp_dir("missing").join("missing").join("log.txt"), "x").unwrap_err();
assert_eq!(err.kind(), ErrorKind::NotFound);
}
#[test]
fn invalid_line() {
for (name, line) in [("newline", "a\nb"), ("cr", "a\rb")] {
let path = temp_dir(name).join("log.txt");
let err = append_line(&path, line).unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidInput);
assert!(!path.exists());
}
}
fn text(w: usize, i: usize) -> String {
format!("writer {w} line {i:03} {}", "x".repeat(40))
}
#[test]
fn many_writers() {
let path = temp_dir("many").join("log.txt");
let (writers, lines) = (8, 250);
let handles: Vec<_> = (0..writers)
.map(|w| {
let path = path.clone();
thread::spawn(move || {
for i in 0..lines {
append_line(&path, &text(w, i)).unwrap();
}
})
})
.collect();
for h in handles {
h.join().unwrap();
}
let mut got: Vec<String> = fs::read_to_string(&path).unwrap().lines().map(String::from).collect();
let mut want: Vec<String> = (0..writers).flat_map(|w| (0..lines).map(move |i| text(w, i))).collect();
got.sort();
want.sort();
assert_eq!(got, want);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/append-to-a-file/.
# append_line PATH LINE
# Adds LINE and one newline to the end of the file PATH, and makes the file if it is missing.
# Returns a nonzero status, and writes nothing, if LINE holds a newline or a CR,
# or if the file cannot be opened.
append_line() {
if [[ $2 == *[$'\r\n']* ]]; then
printf 'append_line: the line must not hold a newline or a CR\n' >&2
return 1
fi
# >> opens the file with O_APPEND. printf sends the line and the newline together.
printf '%s\n' "$2" >>"$1"
}
test_append_line.bats 54 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/append-to-a-file/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/append_line.sh"
file="$BATS_TEST_TMPDIR/log.txt"
}
check() { # check OLD LINE WANT; OLD is "-" when no file is there
local got want
if [[ $1 != - ]]; then printf '%b' "$1" >"$file"; fi
append_line "$file" "$2"
got=$(cat -- "$file" && printf x)
want=$(printf '%b' "$3" && printf x)
[ "$got" = "$want" ]
}
@test "new-file" { check - 'first' 'first\n'; }
@test "append-existing" { check 'one\n' 'two' 'one\ntwo\n'; }
@test "new-file-empty-line" { check - '' '\n'; }
@test "empty-line" { check 'a\n' '' 'a\n\n'; }
@test "empty-file" { check '' 'x' 'x\n'; }
@test "no-final-newline" { check 'one' 'two' 'onetwo\n'; }
@test "crlf-file" { check 'one\r\n' 'two' 'one\r\ntwo\n'; }
@test "whitespace" { check '' $' two spaces\ttab ' ' two spaces\ttab \n'; }
@test "non-ascii" { check 'naïve\n' 'café 日本語 🙂' 'naïve\ncafé 日本語 🙂\n'; }
@test "missing-dir" {
run ! append_line "$BATS_TEST_TMPDIR/missing/log.txt" x
}
@test "newline-in-line" {
run ! append_line "$file" $'a\nb'
[ ! -e "$file" ]
}
@test "cr-in-line" {
run ! append_line "$file" $'a\rb'
[ ! -e "$file" ]
}
@test "many-writers" {
local w i x40
x40=$(printf 'x%.0s' {1..40})
for w in 0 1 2 3 4 5 6 7; do
(for i in $(seq -w 0 249); do append_line "$file" "writer $w line $i $x40"; done) &
done
wait
[ "$(wc -l <"$file")" -eq 2000 ]
[ "$(sort -u -- "$file" | grep -c -E "^writer [0-7] line [0-9]{3} x{40}$")" -eq 2000 ]
}
References
- The Open Group, POSIX.1-2024, write, Description, the paragraph on O_APPEND
- The Open Group, POSIX.1-2024, open, O_APPEND, O_CREAT
- The Open Group, POSIX.1-2024, System Interfaces, General Information, 2.9.7 Thread Interactions with File Operations
- The Open Group, POSIX.1-2024, fopen, the mode a
- Linux manual page, open(2), O_APPEND
- The Python Standard Library, Built-in Functions, open(), the mode 'a'
- The Python Standard Library, os, os.open, os.write, os.O_APPEND
- Node.js documentation, File system, File system flags, 'a'; filehandle.write
- Java SE 25 API, java.nio.file.StandardOpenOption, APPEND
- Java SE 25 API, java.nio.channels.FileChannel, the paragraph on append mode
- Java SE 25 API, java.nio.file.Files, write, writeString
- .NET API reference, FileMode, Append
- .NET API reference, FileShare, None
- .NET API reference, File.AppendAllText
- dotnet/runtime issue 53432, Allow for atomic appends to end of file (2021)
- dotnet/runtime issue 76408, Allow for atomic appends to end of file, Round 2 (2022)
- Go standard library, package os, OpenFile, O_APPEND, O_CREATE
- The Rust Standard Library, std::fs::OpenOptions, append
- cppreference.com, std::ios_base::openmode, app
- GNU Bash Reference Manual, Redirections, Appending Redirected Output
- PowerShell 7.6 reference, Add-Content
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 WZE7MN Edit this page History Report an error Markdown