Programming Search⌘K

Taskcore

Write a file

Also called write a string to a file, save text to a file, append to a file, replace a file atomically, overwrite a file.

Write a string to a file as UTF-8 with no change to its bytes, in one of three modes, truncate, append, or atomic replacement through a temporary file in the same directory.

Task

Write a string to a file. The file holds the UTF-8 bytes of the string and nothing else. There is no byte order mark, and each \n, \r\n and \r stays as it is.

Each solution is a function write_text(path, text, mode). The mode is one of three:

  • truncate: make the file if it does not exist, or cut an existing file to length zero, then write the text.
  • append: make the file if it does not exist, then add the text at its end.
  • atomic: replace the file as one step. Write the text to a new temporary file in the same directory, flush it to the disk, close it, and rename it over the path. On a failure, remove the temporary file.

The atomic mode uses POSIX rename. While the rename runs, a directory entry with the new name stays visible. It refers to the old file or to the new file. So a reader sees the whole old content or the whole new content, and never a part. A rename works only inside one file system, and POSIX gives the error EXDEV for two file systems. For this reason the temporary file goes in the same directory as the target, not in /tmp.

Two more steps make the new content survive a power failure. fsync on the file sends its data to the storage device before the rename. The Linux fsync(2) page adds that this does not put the directory entry on the disk. For that, an fsync on the directory is also needed. The solutions on this page do not sync the directory.

Check the result of close too. The Linux close(2) page says that the error of an earlier write can come only at the final close.

Solutions

  • Python. open(path, "w") truncates and open(path, "a") appends. The solution gives encoding="utf-8", because the default encoding comes from the locale when UTF-8 Mode is off. It also gives newline="". With the default newline=None, Python changes each \n to os.linesep on output. The atomic mode uses tempfile.mkstemp(dir=...), f.flush(), os.fsync and os.replace. os.replace replaces an existing file, and the documentation says that a successful rename is atomic.
  • JavaScript and TypeScript (Node.js). fsPromises.writeFile with the flag "w" (the default) or "a". The atomic mode opens the temporary file with "wx", which fails if the path exists. Then it calls filehandle.writeFile, filehandle.sync and fsPromises.rename. The TypeScript file adds types only.
  • Java. Files.writeString(path, text, UTF_8). With no options, it works as if CREATE, TRUNCATE_EXISTING and WRITE are given. Append mode gives CREATE and APPEND. The atomic mode uses Files.createTempFile(dir, ...), a FileChannel with force(true), and Files.move with ATOMIC_MOVE. The documentation says that, when the target exists, it is specific to the implementation whether ATOMIC_MOVE replaces it or throws an IOException. On macOS, where the tests ran, it replaces the file.
  • C#. File.WriteAllText and File.AppendAllText with new UTF8Encoding(false, true). The false turns off the byte order mark, and the true makes invalid text throw an exception. The atomic mode opens the temporary file with FileMode.CreateNew, then calls Flush(flushToDisk: true) and File.Move(tmp, path, overwrite: true). The File.Move documentation says that a move to another volume is a copy and a delete. So the temporary file must be on the volume of the target.
  • Go. os.WriteFile(path, data, 0o666) truncates. Append mode uses os.OpenFile with O_WRONLY|O_APPEND|O_CREATE, and it returns the error of Close too. The atomic mode uses os.CreateTemp(dir, pattern), File.Sync, Close and os.Rename.
  • Rust. fs::write(path, text) creates or replaces the file. Append mode uses OpenOptions::new().append(true).create(true). The atomic mode makes the temporary file with create_new(true), which fails with AlreadyExists if the name exists. Then it calls write_all, sync_all and fs::rename. The sync_all documentation says that a drop of a File ignores all errors, and sync_all reports them.
  • C. fopen(path, "wb") or fopen(path, "ab"), then fwrite and fclose. The b has no effect on POSIX systems. On Windows it turns off the special handling of '\n'. fclose flushes the buffered data to the operating system, so the solution checks its result. The atomic mode uses POSIX mkstemp, a loop of write, fsync, close and rename.
  • C++. std::ofstream with std::ios::binary and trunc or app, and with exceptions on failbit and badbit. The atomic mode uses POSIX mkstemp, write and fsync, then std::filesystem::rename, which works as if by POSIX rename.
  • Bash. printf '%s' "$text" >"$path" truncates, and >> appends. printf '%s' writes the bytes of the argument with no change. The atomic mode makes the temporary file with mktemp "$path.XXXXXX" and renames it with mv -f. It first refuses a path that is a directory (see the pitfalls). The Bash builtins include no command that syncs a file, so this mode has no fsync.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl. Each case gives the text, the mode, and the content of the file before the call (null when there is no file). The expected value is the content after the call. Each test also checks that the directory holds only out.txt, so no temporary file stays behind.

  • new-file, append-missing and atomic-new: no file before the call. Each mode makes the file.
  • truncate-longer: the old content is longer than the new text. No part of the old content stays.
  • empty-truncate, empty-new and atomic-empty: an empty text gives a file of length zero, and the file exists.
  • append-existing and append-no-newline: append mode adds no newline. one and two give onetwo.
  • non-ascii and atomic-non-ascii: characters of 2, 3 and 4 bytes in UTF-8.
  • crlf and mixed-endings: \r\n and \r stay as they are.
  • backslashes and format-chars: the text C:\temp\new and the text -n 100% %s. These catch a Bash solution that uses echo, or a printf with the text as the format.

The cases in cases/errors.jsonl are failures. The toolchain does not load this file yet, so the test files hold these cases by name:

  • missing-dir-truncate, missing-dir-append and missing-dir-atomic: the parent directory does not exist. Each mode fails with a "not found" error and makes no file.
  • atomic-onto-directory: the path names an empty directory. POSIX rename fails with EISDIR when the new name is a directory and the old name is not. The directory stays, and no temporary file stays.

Pitfalls

  • Truncate mode empties the file first. If the program fails after the open and before the write, the old content is lost. Here the conversion fails after open has cut the file:

This code runs but gives a wrong answer on purpose.

from pathlib import Path

path = Path("config.txt")
path.write_text("port = 80\n", encoding="utf-8")
try:
    with open(path, "w", encoding="utf-8") as f:
        f.write("port = %d\n" % int("eighty"))
except ValueError as e:
    print("error:", e)
print(repr(path.read_text(encoding="utf-8")))
Output
error: invalid literal for int() with base 10: 'eighty'
''

Make the new content before the open, or use the atomic mode.

  • echo changes the text in Bash. echo adds a newline at the end. It reads a first argument -n as an option, and echo does not take -- as the end of the options. printf '%s' writes the argument as it is:

This code runs but gives a wrong answer on purpose.

for text in 'line' '-n'; do
  echo "$text" >echo.txt
  printf '%s' "$text" >printf.txt
  IFS= read -r -d '' a <echo.txt
  IFS= read -r -d '' b <printf.txt
  printf '%s: echo wrote %d bytes, printf wrote %d bytes\n' "$text" "${#a}" "${#b}"
done
Output
line: echo wrote 5 bytes, printf wrote 4 bytes
-n: echo wrote 0 bytes, printf wrote 2 bytes

Do not give the text as the format of printf either. In a format, % starts a format specification and \ starts an escape sequence.

  • mv onto a directory moves the file into it. POSIX mv has a second form: when the last operand is an existing directory, mv moves the file into that directory. So the target does not change, and the command reports no error:

This code runs but gives a wrong answer on purpose.

mkdir out.txt
printf 'new\n' >out.txt.tmp
mv -f out.txt.tmp out.txt
echo "status: $?"
ls out.txt
Output
status: 0
out.txt.tmp

The Bash solution tests [ -d "$path" ] before the move.

  • The atomic mode can change the permissions. POSIX mkstemp makes the file with read and write permission for the owner only. Python tempfile.mkstemp and Go os.CreateTemp do the same. After the rename, the file has the mode of the temporary file, not the old mode:

This code runs but gives a wrong answer on purpose.

import os
import stat
import tempfile

os.umask(0o022)
with open("config.txt", "w", encoding="utf-8") as f:
    f.write("old\n")
print("before:", oct(stat.S_IMODE(os.stat("config.txt").st_mode)))
fd, tmp = tempfile.mkstemp(dir=".")
with open(fd, "w", encoding="utf-8") as f:
    f.write("new\n")
os.replace(tmp, "config.txt")
print("after:", oct(stat.S_IMODE(os.stat("config.txt").st_mode)))
Output
before: 0o644
after: 0o600

If the mode matters, read it from the old file and set it on the temporary file before the rename, for example with os.chmod. The solutions on this page do not copy the mode, and the cases do not check it.

  • Encoding.UTF8 writes a byte order mark in C#. File.WriteAllText(path, text) writes UTF-8 with no byte order mark. With the argument Encoding.UTF8, the file starts with the bytes EF BB BF. new UTF8Encoding(false) gives an encoding with no mark:

This code runs but gives a wrong answer on purpose.

using System.Text;

File.WriteAllText("a.txt", "hi", Encoding.UTF8);
File.WriteAllText("b.txt", "hi", new UTF8Encoding(false));
Console.WriteLine(Convert.ToHexString(File.ReadAllBytes("a.txt")));
Console.WriteLine(Convert.ToHexString(File.ReadAllBytes("b.txt")));
Output
EFBBBF6869
6869
  • APPEND alone does not make the file in Java. When Files.writeString gets options, it uses only those options. APPEND without CREATE fails when the file does not exist:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class Main {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("log.txt");
        try {
            Files.writeString(path, "first\n", StandardOpenOption.APPEND);
        } catch (NoSuchFileException e) {
            System.out.println("APPEND: " + e.getClass().getSimpleName());
        }
        Files.writeString(path, "first\n", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        System.out.print("CREATE, APPEND: " + Files.readString(path));
    }
}
Output
APPEND: NoSuchFileException
CREATE, APPEND: first

Code

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

write_text.pyI0tests passRawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-file/.

import os
import tempfile


def write_text(path: str | os.PathLike[str], text: str, mode: str) -> None:
    """Write text to path as UTF-8, with no change to the line ends.

    mode is "truncate", "append" or "atomic".
    """
    if mode == "atomic":
        _replace(path, text)
        return
    flags = {"truncate": "w", "append": "a"}[mode]
    # newline="" turns off the change of "\n" to os.linesep.
    with open(path, flags, encoding="utf-8", newline="") as file:
        file.write(text)


def _replace(path: str | os.PathLike[str], text: str) -> None:
    # The temporary file is in the same directory, so the rename does not
    # cross a file system.
    directory = os.path.dirname(os.path.abspath(path))
    fd, tmp = tempfile.mkstemp(dir=directory, prefix=".tmp-")
    try:
        with open(fd, "w", encoding="utf-8", newline="") as file:
            file.write(text)
            file.flush()
            os.fsync(file.fileno())
        os.replace(tmp, path)
    except BaseException:
        os.unlink(tmp)
        raise
test_write_text.py 58 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-file/.

import os
from pathlib import Path

import pytest

from write_text import write_text

# name: (text, mode, the file before the call or None, the file after the call)
CASES = {
    "new-file": ("alpha\nbeta\n", "truncate", None, "alpha\nbeta\n"),
    "append-existing": ("two\n", "append", "one\n", "one\ntwo\n"),
    "atomic-replace": ("new\n", "atomic", "old\n", "new\n"),
    "truncate-longer": ("short\n", "truncate", "a much longer old line\n", "short\n"),
    "empty-truncate": ("", "truncate", "old\n", ""),
    "empty-new": ("", "truncate", None, ""),
    "append-missing": ("first\n", "append", None, "first\n"),
    "append-no-newline": ("two", "append", "one", "onetwo"),
    "non-ascii": ("naïve café\n日本語\n🙂\n", "truncate", None, "naïve café\n日本語\n🙂\n"),
    "crlf": ("one\r\ntwo\r\n", "truncate", None, "one\r\ntwo\r\n"),
    "mixed-endings": ("lf\ncrlf\r\ncr\rend", "truncate", None, "lf\ncrlf\r\ncr\rend"),
    "backslashes": ("C:\\temp\\new\n", "truncate", None, "C:\\temp\\new\n"),
    "format-chars": ("-n 100% %s\n", "truncate", None, "-n 100% %s\n"),
    "atomic-new": ("new\n", "atomic", None, "new\n"),
    "atomic-empty": ("", "atomic", "old\n", ""),
    "atomic-non-ascii": ("naïve café\n日本語\n🙂\n", "atomic", "old\n", "naïve café\n日本語\n🙂\n"),
}


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
    text, mode, before, want = CASES[name]
    path = tmp_path / "out.txt"
    if before is not None:
        path.write_bytes(before.encode())
    write_text(path, text, mode)
    # The exact bytes: UTF-8, no byte order mark, no change to the line ends.
    assert path.read_bytes() == want.encode()
    # No temporary file stays in the directory.
    assert os.listdir(tmp_path) == ["out.txt"]


@pytest.mark.parametrize("mode", ["truncate", "append", "atomic"])
def test_missing_dir(tmp_path: Path, mode: str) -> None:
    with pytest.raises(FileNotFoundError):
        write_text(tmp_path / "missing" / "out.txt", "x\n", mode)
    assert os.listdir(tmp_path) == []


def test_atomic_onto_directory(tmp_path: Path) -> None:
    path = tmp_path / "out.txt"
    path.mkdir()
    with pytest.raises(OSError):
        write_text(path, "x\n", "atomic")
    assert path.is_dir()
    assert os.listdir(tmp_path) == ["out.txt"]
write_text.cppI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

#include "write_text.hpp"

#include <cerrno>
#include <fstream>
#include <string>
#include <system_error>
#include <vector>

#include <stdlib.h>
#include <unistd.h>

namespace fs = std::filesystem;

namespace {

// binary means no change to the line ends on any system.
void write_stream(const fs::path &path, std::string_view text, std::ios::openmode how) {
    std::ofstream out;
    out.exceptions(std::ios::failbit | std::ios::badbit);
    out.open(path, std::ios::binary | how);
    out.write(text.data(), static_cast<std::streamsize>(text.size()));
    // close flushes the buffer, so it can report a write error too.
    out.close();
}

[[noreturn]] void fail(const char *what, const fs::path &path) {
    throw fs::filesystem_error(what, path, std::error_code(errno, std::generic_category()));
}

// This part uses POSIX for the temporary file: mkstemp, write and fsync.
void replace(const fs::path &path, std::string_view text) {
    // The temporary file is in the same directory, so the rename does not
    // cross a file system.
    std::string name = path.string() + ".XXXXXX";
    std::vector<char> tmp(name.begin(), name.end());
    tmp.push_back('\0');
    int fd = mkstemp(tmp.data());
    if (fd < 0) {
        fail("mkstemp", path);
    }
    try {
        std::string_view rest = text;
        while (!rest.empty()) {
            ssize_t n = write(fd, rest.data(), rest.size());
            if (n < 0 && errno != EINTR) {
                fail("write", tmp.data());
            }
            if (n > 0) {
                rest.remove_prefix(static_cast<std::size_t>(n));
            }
        }
        if (fsync(fd) != 0) {
            fail("fsync", tmp.data());
        }
        int closed = close(fd);
        fd = -1;
        if (closed != 0) {
            fail("close", tmp.data());
        }
        fs::rename(tmp.data(), path);
    } catch (...) {
        if (fd >= 0) {
            close(fd);
        }
        std::error_code ignored;
        fs::remove(tmp.data(), ignored);
        throw;
    }
}

} // namespace

void write_text(const fs::path &path, std::string_view text, WriteMode mode) {
    switch (mode) {
    case WriteMode::Truncate:
        write_stream(path, text, std::ios::trunc);
        return;
    case WriteMode::Append:
        write_stream(path, text, std::ios::app);
        return;
    case WriteMode::Atomic:
        replace(path, text);
        return;
    }
}
write_text.hpp 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

#pragma once

#include <filesystem>
#include <string_view>

enum class WriteMode { Truncate, Append, Atomic };

// Writes text to path, with no change to the bytes. It throws
// std::filesystem::filesystem_error or std::ios_base::failure on an error.
void write_text(const std::filesystem::path &path, std::string_view text, WriteMode mode);
test_write_text.cpp 143 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

#include "write_text.hpp"

#include <array>
#include <exception>
#include <fstream>
#include <iostream>
#include <iterator>
#include <optional>
#include <string>
#include <string_view>
#include <vector>

#include <stdlib.h>
#include <unistd.h>

namespace fs = std::filesystem;

namespace {

struct Case {
    std::string_view name;
    std::string_view text;
    WriteMode mode;
    std::optional<std::string_view> before;
    std::string_view want;
};

constexpr std::string_view non_ascii = "naïve café\n日本語\n🙂\n";

const std::array cases{
    Case{"new-file", "alpha\nbeta\n", WriteMode::Truncate, std::nullopt, "alpha\nbeta\n"},
    Case{"append-existing", "two\n", WriteMode::Append, "one\n", "one\ntwo\n"},
    Case{"atomic-replace", "new\n", WriteMode::Atomic, "old\n", "new\n"},
    Case{"truncate-longer", "short\n", WriteMode::Truncate, "a much longer old line\n", "short\n"},
    Case{"empty-truncate", "", WriteMode::Truncate, "old\n", ""},
    Case{"empty-new", "", WriteMode::Truncate, std::nullopt, ""},
    Case{"append-missing", "first\n", WriteMode::Append, std::nullopt, "first\n"},
    Case{"append-no-newline", "two", WriteMode::Append, "one", "onetwo"},
    Case{"non-ascii", non_ascii, WriteMode::Truncate, std::nullopt, non_ascii},
    Case{"crlf", "one\r\ntwo\r\n", WriteMode::Truncate, std::nullopt, "one\r\ntwo\r\n"},
    Case{"mixed-endings", "lf\ncrlf\r\ncr\rend", WriteMode::Truncate, std::nullopt, "lf\ncrlf\r\ncr\rend"},
    Case{"backslashes", "C:\\temp\\new\n", WriteMode::Truncate, std::nullopt, "C:\\temp\\new\n"},
    Case{"format-chars", "-n 100% %s\n", WriteMode::Truncate, std::nullopt, "-n 100% %s\n"},
    Case{"atomic-new", "new\n", WriteMode::Atomic, std::nullopt, "new\n"},
    Case{"atomic-empty", "", WriteMode::Atomic, "old\n", ""},
    Case{"atomic-non-ascii", non_ascii, WriteMode::Atomic, "old\n", non_ascii},
};

fs::path make_dir() {
    std::string name = (fs::temp_directory_path() / "write-text-XXXXXX").string();
    std::vector<char> buf(name.begin(), name.end());
    buf.push_back('\0');
    if (mkdtemp(buf.data()) == nullptr) {
        throw std::runtime_error("mkdtemp failed");
    }
    return buf.data();
}

std::vector<std::string> names(const fs::path &dir) {
    std::vector<std::string> out;
    for (const auto &e : fs::directory_iterator(dir)) {
        out.push_back(e.path().filename().string());
    }
    return out;
}

std::string slurp(const fs::path &path) {
    std::ifstream in(path, std::ios::binary);
    return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
}

} // namespace

int main() {
    int failures = 0;
    const std::vector<std::string> only{"out.txt"};
    try {
        for (const Case &c : cases) {
            fs::path dir = make_dir();
            fs::path path = dir / "out.txt";
            if (c.before) {
                write_text(path, *c.before, WriteMode::Truncate);
            }
            try {
                write_text(path, c.text, c.mode);
                if (slurp(path) != c.want) {
                    std::cout << "FAIL " << c.name << ": wrong bytes\n";
                    failures++;
                } else if (names(dir) != only) {
                    std::cout << "FAIL " << c.name << ": other files in the directory\n";
                    failures++;
                }
            } catch (const std::exception &e) {
                std::cout << "FAIL " << c.name << ": " << e.what() << '\n';
                failures++;
            }
            fs::remove_all(dir);
        }

        const std::array<std::pair<std::string_view, WriteMode>, 3> modes{{
            {"truncate", WriteMode::Truncate},
            {"append", WriteMode::Append},
            {"atomic", WriteMode::Atomic},
        }};
        for (const auto &[name, mode] : modes) {
            fs::path dir = make_dir();
            bool threw = false;
            try {
                write_text(dir / "missing" / "out.txt", "x\n", mode);
            } catch (const std::exception &) {
                threw = true;
            }
            if (!threw || !names(dir).empty()) {
                std::cout << "FAIL missing-dir-" << name << '\n';
                failures++;
            }
            fs::remove_all(dir);
        }

        fs::path dir = make_dir();
        fs::path path = dir / "out.txt";
        fs::create_directory(path);
        bool threw = false;
        try {
            write_text(path, "x\n", WriteMode::Atomic);
        } catch (const fs::filesystem_error &) {
            threw = true;
        }
        if (!threw || !fs::is_directory(path) || names(dir) != only) {
            std::cout << "FAIL atomic-onto-directory\n";
            failures++;
        }
        fs::remove_all(dir);
    } catch (const std::exception &e) {
        std::cout << "FAIL setup: " << e.what() << '\n';
        return 1;
    }
    std::cout << failures << " failures\n";
    return failures == 0 ? 0 : 1;
}
WriteText.javaI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.WRITE;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public final class WriteText {
  private WriteText() {}

  /** The modes of {@link #writeText}. */
  public enum Mode {
    TRUNCATE,
    APPEND,
    ATOMIC
  }

  /** Writes text to path as UTF-8, with no change to the line ends. */
  public static void writeText(Path path, String text, Mode mode) throws IOException {
    switch (mode) {
      // With no options, writeString creates or truncates the file.
      case TRUNCATE -> Files.writeString(path, text, StandardCharsets.UTF_8);
      case APPEND -> Files.writeString(path, text, StandardCharsets.UTF_8, CREATE, APPEND);
      case ATOMIC -> replace(path, text);
    }
  }

  private static void replace(Path path, String text) throws IOException {
    // The temporary file is in the same directory, so the move does not
    // cross a file system.
    Path tmp = Files.createTempFile(path.toAbsolutePath().getParent(), ".tmp-", ".part");
    try {
      try (FileChannel channel = FileChannel.open(tmp, WRITE)) {
        ByteBuffer bytes = ByteBuffer.wrap(text.getBytes(StandardCharsets.UTF_8));
        while (bytes.hasRemaining()) {
          channel.write(bytes);
        }
        channel.force(true);
      }
      Files.move(tmp, path, StandardCopyOption.ATOMIC_MOVE);
    } catch (IOException | RuntimeException e) {
      Files.deleteIfExists(tmp);
      throw e;
    }
  }
}
WriteTextTest.java 84 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

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

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.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.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;

class WriteTextTest {
  @TempDir Path dir;

  static Stream<Arguments> cases() {
    String nonAscii = "naïve café\n日本語\n🙂\n";
    return Stream.of(
        Arguments.of("new-file", "alpha\nbeta\n", "TRUNCATE", null, "alpha\nbeta\n"),
        Arguments.of("append-existing", "two\n", "APPEND", "one\n", "one\ntwo\n"),
        Arguments.of("atomic-replace", "new\n", "ATOMIC", "old\n", "new\n"),
        Arguments.of(
            "truncate-longer", "short\n", "TRUNCATE", "a much longer old line\n", "short\n"),
        Arguments.of("empty-truncate", "", "TRUNCATE", "old\n", ""),
        Arguments.of("empty-new", "", "TRUNCATE", null, ""),
        Arguments.of("append-missing", "first\n", "APPEND", null, "first\n"),
        Arguments.of("append-no-newline", "two", "APPEND", "one", "onetwo"),
        Arguments.of("non-ascii", nonAscii, "TRUNCATE", null, nonAscii),
        Arguments.of("crlf", "one\r\ntwo\r\n", "TRUNCATE", null, "one\r\ntwo\r\n"),
        Arguments.of(
            "mixed-endings", "lf\ncrlf\r\ncr\rend", "TRUNCATE", null, "lf\ncrlf\r\ncr\rend"),
        Arguments.of("backslashes", "C:\\temp\\new\n", "TRUNCATE", null, "C:\\temp\\new\n"),
        Arguments.of("format-chars", "-n 100% %s\n", "TRUNCATE", null, "-n 100% %s\n"),
        Arguments.of("atomic-new", "new\n", "ATOMIC", null, "new\n"),
        Arguments.of("atomic-empty", "", "ATOMIC", "old\n", ""),
        Arguments.of("atomic-non-ascii", nonAscii, "ATOMIC", "old\n", nonAscii));
  }

  private List<String> names() throws IOException {
    try (Stream<Path> files = Files.list(dir)) {
      return files.map(p -> p.getFileName().toString()).toList();
    }
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void writesTheBytes(String name, String text, String mode, String before, String want)
      throws IOException {
    Path path = dir.resolve("out.txt");
    if (before != null) {
      Files.write(path, before.getBytes(StandardCharsets.UTF_8));
    }
    WriteText.writeText(path, text, WriteText.Mode.valueOf(mode));
    // The exact bytes: UTF-8, no byte order mark, no change to the line ends.
    assertArrayEquals(want.getBytes(StandardCharsets.UTF_8), Files.readAllBytes(path), name);
    assertEquals(List.of("out.txt"), names(), name);
  }

  @ParameterizedTest
  @EnumSource(WriteText.Mode.class)
  void missingDirectory(WriteText.Mode mode) throws IOException {
    Path path = dir.resolve("missing").resolve("out.txt");
    assertThrows(NoSuchFileException.class, () -> WriteText.writeText(path, "x\n", mode));
    assertEquals(List.of(), names());
  }

  @Test
  void atomicOntoDirectory() throws IOException {
    Path path = Files.createDirectory(dir.resolve("out.txt"));
    assertThrows(IOException.class, () -> WriteText.writeText(path, "x\n", WriteText.Mode.ATOMIC));
    assertTrue(Files.isDirectory(path));
    assertEquals(List.of("out.txt"), names());
  }
}
write_text.cI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

#define _POSIX_C_SOURCE 200809L

#include "write_text.h"

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

// "wb" truncates or creates; "ab" appends or creates. The b means no change
// to the line ends on any system.
static int write_stdio(const char *path, const char *text, size_t len, const char *how) {
    FILE *f = fopen(path, how);
    if (f == NULL) {
        return -1;
    }
    size_t n = fwrite(text, 1, len, f);
    int saved = errno;
    // fclose flushes the buffer, so it can report a write error too.
    if (fclose(f) != 0) {
        return -1;
    }
    if (n != len) {
        errno = saved;
        return -1;
    }
    return 0;
}

static int write_all(int fd, const char *text, size_t len) {
    while (len > 0) {
        ssize_t n = write(fd, text, len);
        if (n < 0) {
            if (errno == EINTR) {
                continue;
            }
            return -1;
        }
        text += n;
        len -= (size_t)n;
    }
    return 0;
}

static int replace(const char *path, const char *text, size_t len) {
    // The temporary file is in the same directory, so the rename does not
    // cross a file system.
    size_t plen = strlen(path);
    char *tmp = malloc(plen + sizeof ".XXXXXX");
    if (tmp == NULL) {
        return -1;
    }
    memcpy(tmp, path, plen);
    memcpy(tmp + plen, ".XXXXXX", sizeof ".XXXXXX");
    int fd = mkstemp(tmp);
    if (fd < 0) {
        free(tmp);
        return -1;
    }
    int failed = write_all(fd, text, len) != 0 || fsync(fd) != 0;
    int saved = errno;
    if (close(fd) != 0 && !failed) {
        failed = 1;
        saved = errno;
    }
    if (!failed && rename(tmp, path) != 0) {
        failed = 1;
        saved = errno;
    }
    if (failed) {
        unlink(tmp);
        errno = saved;
    }
    free(tmp);
    return failed ? -1 : 0;
}

int write_text(const char *path, const char *text, size_t len, enum write_mode mode) {
    switch (mode) {
    case WRITE_TRUNCATE:
        return write_stdio(path, text, len, "wb");
    case WRITE_APPEND:
        return write_stdio(path, text, len, "ab");
    case WRITE_ATOMIC:
        return replace(path, text, len);
    }
    errno = EINVAL;
    return -1;
}
write_text.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

#ifndef WRITE_TEXT_H
#define WRITE_TEXT_H

#include <stddef.h>

enum write_mode { WRITE_TRUNCATE, WRITE_APPEND, WRITE_ATOMIC };

// Writes the len bytes of text to path. It returns 0, or -1 with errno set.
int write_text(const char *path, const char *text, size_t len, enum write_mode mode);

#endif
test_write_text.c 164 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

#define _POSIX_C_SOURCE 200809L

#include "write_text.h"

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

#define NON_ASCII "na\xc3\xafve caf\xc3\xa9\n\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\n\xf0\x9f\x99\x82\n"

struct test_case {
    const char *name;
    const char *text;
    enum write_mode mode;
    const char *before; // NULL: no file before the call
    const char *want;
};

static const struct test_case cases[] = {
    {"new-file", "alpha\nbeta\n", WRITE_TRUNCATE, NULL, "alpha\nbeta\n"},
    {"append-existing", "two\n", WRITE_APPEND, "one\n", "one\ntwo\n"},
    {"atomic-replace", "new\n", WRITE_ATOMIC, "old\n", "new\n"},
    {"truncate-longer", "short\n", WRITE_TRUNCATE, "a much longer old line\n", "short\n"},
    {"empty-truncate", "", WRITE_TRUNCATE, "old\n", ""},
    {"empty-new", "", WRITE_TRUNCATE, NULL, ""},
    {"append-missing", "first\n", WRITE_APPEND, NULL, "first\n"},
    {"append-no-newline", "two", WRITE_APPEND, "one", "onetwo"},
    {"non-ascii", NON_ASCII, WRITE_TRUNCATE, NULL, NON_ASCII},
    {"crlf", "one\r\ntwo\r\n", WRITE_TRUNCATE, NULL, "one\r\ntwo\r\n"},
    {"mixed-endings", "lf\ncrlf\r\ncr\rend", WRITE_TRUNCATE, NULL, "lf\ncrlf\r\ncr\rend"},
    {"backslashes", "C:\\temp\\new\n", WRITE_TRUNCATE, NULL, "C:\\temp\\new\n"},
    {"format-chars", "-n 100% %s\n", WRITE_TRUNCATE, NULL, "-n 100% %s\n"},
    {"atomic-new", "new\n", WRITE_ATOMIC, NULL, "new\n"},
    {"atomic-empty", "", WRITE_ATOMIC, "old\n", ""},
    {"atomic-non-ascii", NON_ASCII, WRITE_ATOMIC, "old\n", NON_ASCII},
};

// The number of entries in dir, and the name of the last one.
static int count(const char *dir, char *last, size_t size) {
    DIR *d = opendir(dir);
    if (d == NULL) {
        return -1;
    }
    int n = 0;
    struct dirent *e;
    while ((e = readdir(d)) != NULL) {
        if (strcmp(e->d_name, ".") != 0 && strcmp(e->d_name, "..") != 0) {
            n++;
            snprintf(last, size, "%s", e->d_name);
        }
    }
    closedir(d);
    return n;
}

static int only_out(const char *dir) {
    char last[256] = "";
    return count(dir, last, sizeof last) == 1 && strcmp(last, "out.txt") == 0;
}

// Reads the file into buf. It returns the length, or -1.
static long slurp(const char *path, char *buf, size_t size) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        return -1;
    }
    size_t n = fread(buf, 1, size, f);
    fclose(f);
    return (long)n;
}

static void cleanup(const char *dir, const char *path) {
    struct stat st;
    if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) {
        rmdir(path);
    } else {
        remove(path);
    }
    rmdir(dir);
}

// Makes a new empty directory with a name from the process id and a count.
static int make_dir(char *dir, size_t size) {
    static int n = 0;
    snprintf(dir, size, "/tmp/write-text-%ld-%d", (long)getpid(), n++);
    return mkdir(dir, 0700);
}

int main(void) {
    int failures = 0;
    char path[512];
    char buf[256];
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        char dir[64];
        if (make_dir(dir, sizeof dir) != 0) {
            perror("mkdir");
            return 1;
        }
        snprintf(path, sizeof path, "%s/out.txt", dir);
        if (c->before != NULL) {
            write_text(path, c->before, strlen(c->before), WRITE_TRUNCATE);
        }
        size_t wlen = strlen(c->want);
        if (write_text(path, c->text, strlen(c->text), c->mode) != 0) {
            printf("FAIL %s: %s\n", c->name, strerror(errno));
            failures++;
        } else if (slurp(path, buf, sizeof buf) != (long)wlen || memcmp(buf, c->want, wlen) != 0) {
            printf("FAIL %s: wrong bytes\n", c->name);
            failures++;
        } else if (!only_out(dir)) {
            printf("FAIL %s: other files in the directory\n", c->name);
            failures++;
        }
        cleanup(dir, path);
    }

    static const char *const names[] = {"truncate", "append", "atomic"};
    for (int m = WRITE_TRUNCATE; m <= WRITE_ATOMIC; m++) {
        char dir[64];
        if (make_dir(dir, sizeof dir) != 0) {
            perror("mkdir");
            return 1;
        }
        snprintf(path, sizeof path, "%s/missing/out.txt", dir);
        char last[256] = "";
        errno = 0;
        if (write_text(path, "x\n", 2, (enum write_mode)m) != -1 || errno != ENOENT) {
            printf("FAIL missing-dir-%s: no ENOENT\n", names[m]);
            failures++;
        } else if (count(dir, last, sizeof last) != 0) {
            printf("FAIL missing-dir-%s: files in the directory\n", names[m]);
            failures++;
        }
        rmdir(dir);
    }

    char dir[64];
    if (make_dir(dir, sizeof dir) != 0) {
        perror("mkdir");
        return 1;
    }
    snprintf(path, sizeof path, "%s/out.txt", dir);
    mkdir(path, 0777);
    struct stat st;
    if (write_text(path, "x\n", 2, WRITE_ATOMIC) != -1) {
        printf("FAIL atomic-onto-directory: no error\n");
        failures++;
    } else if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode) || !only_out(dir)) {
        printf("FAIL atomic-onto-directory: the directory changed\n");
        failures++;
    }
    cleanup(dir, path);

    printf("%d failures\n", failures);
    return failures == 0 ? 0 : 1;
}
WriteText.csI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

using System.Text;

public enum WriteMode
{
    Truncate,
    Append,
    Atomic,
}

public static class WriteFile
{
    // Encoding.UTF8 writes a byte order mark. This encoding writes none, and
    // it throws on a string that is not valid UTF-16.
    private static readonly UTF8Encoding Utf8NoBom = new(false, true);

    // Writes text to path as UTF-8, with no change to the line ends.
    public static void WriteText(string path, string text, WriteMode mode)
    {
        switch (mode)
        {
            case WriteMode.Truncate:
                File.WriteAllText(path, text, Utf8NoBom);
                break;
            case WriteMode.Append:
                File.AppendAllText(path, text, Utf8NoBom);
                break;
            case WriteMode.Atomic:
                Replace(path, text);
                break;
            default:
                throw new ArgumentOutOfRangeException(nameof(mode));
        }
    }

    private static void Replace(string path, string text)
    {
        // The temporary file is in the same directory, so the move does not
        // cross a file system. FileMode.CreateNew fails if the name exists.
        string full = Path.GetFullPath(path);
        string tmp = Path.Combine(Path.GetDirectoryName(full)!, $".{Path.GetFileName(full)}.{Guid.NewGuid():N}.tmp");
        var stream = new FileStream(tmp, FileMode.CreateNew, FileAccess.Write);
        try
        {
            using (stream)
            {
                stream.Write(Utf8NoBom.GetBytes(text));
                stream.Flush(flushToDisk: true);
            }
            File.Move(tmp, full, overwrite: true);
        }
        catch
        {
            File.Delete(tmp);
            throw;
        }
    }
}
WriteTextTests.cs 69 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

using System.Text;
using Xunit;

public sealed class WriteTextTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("write-text-").FullName;

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

    private string[] Names() => Directory.GetFileSystemEntries(dir).Select(Path.GetFileName).ToArray()!;

    public static TheoryData<string, string, WriteMode, string?, string> Cases => new()
    {
        { "new-file", "alpha\nbeta\n", WriteMode.Truncate, null, "alpha\nbeta\n" },
        { "append-existing", "two\n", WriteMode.Append, "one\n", "one\ntwo\n" },
        { "atomic-replace", "new\n", WriteMode.Atomic, "old\n", "new\n" },
        { "truncate-longer", "short\n", WriteMode.Truncate, "a much longer old line\n", "short\n" },
        { "empty-truncate", "", WriteMode.Truncate, "old\n", "" },
        { "empty-new", "", WriteMode.Truncate, null, "" },
        { "append-missing", "first\n", WriteMode.Append, null, "first\n" },
        { "append-no-newline", "two", WriteMode.Append, "one", "onetwo" },
        { "non-ascii", "naïve café\n日本語\n🙂\n", WriteMode.Truncate, null, "naïve café\n日本語\n🙂\n" },
        { "crlf", "one\r\ntwo\r\n", WriteMode.Truncate, null, "one\r\ntwo\r\n" },
        { "mixed-endings", "lf\ncrlf\r\ncr\rend", WriteMode.Truncate, null, "lf\ncrlf\r\ncr\rend" },
        { "backslashes", "C:\\temp\\new\n", WriteMode.Truncate, null, "C:\\temp\\new\n" },
        { "format-chars", "-n 100% %s\n", WriteMode.Truncate, null, "-n 100% %s\n" },
        { "atomic-new", "new\n", WriteMode.Atomic, null, "new\n" },
        { "atomic-empty", "", WriteMode.Atomic, "old\n", "" },
        { "atomic-non-ascii", "naïve café\n日本語\n🙂\n", WriteMode.Atomic, "old\n", "naïve café\n日本語\n🙂\n" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void WritesTheBytes(string name, string text, WriteMode mode, string? before, string want)
    {
        string path = Path.Combine(dir, "out.txt");
        if (before is not null)
        {
            File.WriteAllBytes(path, Encoding.UTF8.GetBytes(before));
        }
        WriteFile.WriteText(path, text, mode);
        // The exact bytes: UTF-8, no byte order mark, no change to the line ends.
        Assert.True(Encoding.UTF8.GetBytes(want).SequenceEqual(File.ReadAllBytes(path)), name);
        Assert.Equal(["out.txt"], Names());
    }

    [Theory]
    [InlineData(WriteMode.Truncate)]
    [InlineData(WriteMode.Append)]
    [InlineData(WriteMode.Atomic)]
    public void MissingDirectory(WriteMode mode)
    {
        string path = Path.Combine(dir, "missing", "out.txt");
        Assert.Throws<DirectoryNotFoundException>(() => WriteFile.WriteText(path, "x\n", mode));
        Assert.Empty(Names());
    }

    [Fact]
    public void AtomicOntoDirectory()
    {
        string path = Directory.CreateDirectory(Path.Combine(dir, "out.txt")).FullName;
        Assert.ThrowsAny<IOException>(() => WriteFile.WriteText(path, "x\n", WriteMode.Atomic));
        Assert.True(Directory.Exists(path));
        Assert.Equal(["out.txt"], Names());
    }
}
writeText.jsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

import { randomUUID } from "node:crypto";
import { open, rename, rm, writeFile } from "node:fs/promises";
import { basename, dirname, join } from "node:path";

/**
 * Writes text to file as UTF-8, with no change to the line ends.
 * @param {string} file
 * @param {string} text
 * @param {"truncate" | "append" | "atomic"} mode
 * @returns {Promise<void>}
 */
export async function writeText(file, text, mode) {
  if (mode === "truncate" || mode === "append") {
    // The flag "w" truncates or creates the file; "a" appends or creates it.
    await writeFile(file, text, { encoding: "utf8", flag: mode === "truncate" ? "w" : "a" });
    return;
  }
  if (mode !== "atomic") throw new RangeError(`unknown mode ${mode}`);
  // Node.js has no function that makes a temporary file. "wx" fails if the name exists.
  const tmp = join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`);
  const handle = await open(tmp, "wx");
  try {
    try {
      await handle.writeFile(text, "utf8");
      await handle.sync();
    } finally {
      await handle.close();
    }
    await rename(tmp, file);
  } catch (error) {
    await rm(tmp, { force: true });
    throw error;
  }
}
writeText.test.js 71 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

import assert from "node:assert/strict";
import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";

import { writeText } from "./writeText.js";

// [case, text, mode, the file before the call or null, the file after the call]
const cases = [
  ["new-file", "alpha\nbeta\n", "truncate", null, "alpha\nbeta\n"],
  ["append-existing", "two\n", "append", "one\n", "one\ntwo\n"],
  ["atomic-replace", "new\n", "atomic", "old\n", "new\n"],
  ["truncate-longer", "short\n", "truncate", "a much longer old line\n", "short\n"],
  ["empty-truncate", "", "truncate", "old\n", ""],
  ["empty-new", "", "truncate", null, ""],
  ["append-missing", "first\n", "append", null, "first\n"],
  ["append-no-newline", "two", "append", "one", "onetwo"],
  ["non-ascii", "naïve café\n日本語\n🙂\n", "truncate", null, "naïve café\n日本語\n🙂\n"],
  ["crlf", "one\r\ntwo\r\n", "truncate", null, "one\r\ntwo\r\n"],
  ["mixed-endings", "lf\ncrlf\r\ncr\rend", "truncate", null, "lf\ncrlf\r\ncr\rend"],
  ["backslashes", "C:\\temp\\new\n", "truncate", null, "C:\\temp\\new\n"],
  ["format-chars", "-n 100% %s\n", "truncate", null, "-n 100% %s\n"],
  ["atomic-new", "new\n", "atomic", null, "new\n"],
  ["atomic-empty", "", "atomic", "old\n", ""],
  ["atomic-non-ascii", "naïve café\n日本語\n🙂\n", "atomic", "old\n", "naïve café\n日本語\n🙂\n"],
];

async function withDir(body) {
  const dir = await mkdtemp(join(tmpdir(), "write-text-"));
  try {
    await body(dir);
  } finally {
    await rm(dir, { recursive: true, force: true });
  }
}

for (const [name, text, mode, before, want] of cases) {
  test(name, () =>
    withDir(async (dir) => {
      const file = join(dir, "out.txt");
      if (before !== null) await writeFile(file, Buffer.from(before, "utf8"));
      await writeText(file, text, mode);
      // The exact bytes: UTF-8, no byte order mark, no change to the line ends.
      assert.deepEqual(await readFile(file), Buffer.from(want, "utf8"));
      assert.deepEqual(await readdir(dir), ["out.txt"]);
    }),
  );
}

for (const mode of ["truncate", "append", "atomic"]) {
  test(`missing-dir-${mode}`, () =>
    withDir(async (dir) => {
      await assert.rejects(writeText(join(dir, "missing", "out.txt"), "x\n", mode), { code: "ENOENT" });
      assert.deepEqual(await readdir(dir), []);
    }),
  );
}

test("atomic-onto-directory", () =>
  withDir(async (dir) => {
    const file = join(dir, "out.txt");
    await mkdir(file);
    await assert.rejects(writeText(file, "x\n", "atomic"));
    assert.ok((await stat(file)).isDirectory());
    assert.deepEqual(await readdir(dir), ["out.txt"]);
  }),
);
writeText.tsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

import { randomUUID } from "node:crypto";
import { open, rename, rm, writeFile } from "node:fs/promises";
import { basename, dirname, join } from "node:path";

export type WriteMode = "truncate" | "append" | "atomic";

// Writes text to file as UTF-8, with no change to the line ends.
export async function writeText(file: string, text: string, mode: WriteMode): Promise<void> {
  if (mode === "truncate" || mode === "append") {
    // The flag "w" truncates or creates the file; "a" appends or creates it.
    await writeFile(file, text, { encoding: "utf8", flag: mode === "truncate" ? "w" : "a" });
    return;
  }
  // Node.js has no function that makes a temporary file. "wx" fails if the name exists.
  const tmp = join(dirname(file), `.${basename(file)}.${randomUUID()}.tmp`);
  const handle = await open(tmp, "wx");
  try {
    try {
      await handle.writeFile(text, "utf8");
      await handle.sync();
    } finally {
      await handle.close();
    }
    await rename(tmp, file);
  } catch (error) {
    await rm(tmp, { force: true });
    throw error;
  }
}
writeText.test.ts 71 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

import assert from "node:assert/strict";
import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";

import { writeText } from "./writeText.ts";

// [case, text, mode, the file before the call or null, the file after the call]
const cases: [string, string, "truncate" | "append" | "atomic", string | null, string][] = [
  ["new-file", "alpha\nbeta\n", "truncate", null, "alpha\nbeta\n"],
  ["append-existing", "two\n", "append", "one\n", "one\ntwo\n"],
  ["atomic-replace", "new\n", "atomic", "old\n", "new\n"],
  ["truncate-longer", "short\n", "truncate", "a much longer old line\n", "short\n"],
  ["empty-truncate", "", "truncate", "old\n", ""],
  ["empty-new", "", "truncate", null, ""],
  ["append-missing", "first\n", "append", null, "first\n"],
  ["append-no-newline", "two", "append", "one", "onetwo"],
  ["non-ascii", "naïve café\n日本語\n🙂\n", "truncate", null, "naïve café\n日本語\n🙂\n"],
  ["crlf", "one\r\ntwo\r\n", "truncate", null, "one\r\ntwo\r\n"],
  ["mixed-endings", "lf\ncrlf\r\ncr\rend", "truncate", null, "lf\ncrlf\r\ncr\rend"],
  ["backslashes", "C:\\temp\\new\n", "truncate", null, "C:\\temp\\new\n"],
  ["format-chars", "-n 100% %s\n", "truncate", null, "-n 100% %s\n"],
  ["atomic-new", "new\n", "atomic", null, "new\n"],
  ["atomic-empty", "", "atomic", "old\n", ""],
  ["atomic-non-ascii", "naïve café\n日本語\n🙂\n", "atomic", "old\n", "naïve café\n日本語\n🙂\n"],
];

async function withDir(body: (dir: string) => Promise<void>): Promise<void> {
  const dir = await mkdtemp(join(tmpdir(), "write-text-"));
  try {
    await body(dir);
  } finally {
    await rm(dir, { recursive: true, force: true });
  }
}

for (const [name, text, mode, before, want] of cases) {
  test(name, () =>
    withDir(async (dir) => {
      const file = join(dir, "out.txt");
      if (before !== null) await writeFile(file, Buffer.from(before, "utf8"));
      await writeText(file, text, mode);
      // The exact bytes: UTF-8, no byte order mark, no change to the line ends.
      assert.deepEqual(await readFile(file), Buffer.from(want, "utf8"));
      assert.deepEqual(await readdir(dir), ["out.txt"]);
    }),
  );
}

for (const mode of ["truncate", "append", "atomic"] as const) {
  test(`missing-dir-${mode}`, () =>
    withDir(async (dir) => {
      await assert.rejects(writeText(join(dir, "missing", "out.txt"), "x\n", mode), { code: "ENOENT" });
      assert.deepEqual(await readdir(dir), []);
    }),
  );
}

test("atomic-onto-directory", () =>
  withDir(async (dir) => {
    const file = join(dir, "out.txt");
    await mkdir(file);
    await assert.rejects(writeText(file, "x\n", "atomic"));
    assert.ok((await stat(file)).isDirectory());
    assert.deepEqual(await readdir(dir), ["out.txt"]);
  }),
);
write_text.goI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

// Package writetext writes a string to a file in one of three modes.
package writetext

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
)

// The modes of WriteText.
const (
	Truncate = "truncate"
	Append   = "append"
	Atomic   = "atomic"
)

// WriteText writes text to path. A Go string holds bytes, so the bytes go to
// the file with no change: no encoding step and no change of the line ends.
func WriteText(path, text, mode string) error {
	switch mode {
	case Truncate:
		// WriteFile creates or truncates the file. 0o666 is the mode before the umask.
		return os.WriteFile(path, []byte(text), 0o666)
	case Append:
		return appendText(path, text)
	case Atomic:
		return replace(path, text)
	}
	return fmt.Errorf("unknown mode %q", mode)
}

func appendText(path, text string) error {
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o666)
	if err != nil {
		return err
	}
	_, err = f.WriteString(text)
	// Close can report a write error, so its error counts too.
	return errors.Join(err, f.Close())
}

func replace(path, text string) (err error) {
	// The temporary file is in the same directory, so the rename does not
	// cross a file system.
	f, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*.tmp")
	if err != nil {
		return err
	}
	defer func() {
		if err != nil {
			os.Remove(f.Name())
		}
	}()
	_, err = f.WriteString(text)
	if err == nil {
		err = f.Sync()
	}
	if err = errors.Join(err, f.Close()); err != nil {
		return err
	}
	return os.Rename(f.Name(), path)
}
write_text_test.go 106 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

package writetext

import (
	"errors"
	"io/fs"
	"os"
	"path/filepath"
	"slices"
	"testing"
)

func names(t *testing.T, dir string) []string {
	t.Helper()
	entries, err := os.ReadDir(dir)
	if err != nil {
		t.Fatal(err)
	}
	var out []string
	for _, e := range entries {
		out = append(out, e.Name())
	}
	return out
}

func TestCases(t *testing.T) {
	none := "\x00none" // no file before the call
	cases := []struct {
		name, text, mode, before, want string
	}{
		{"new-file", "alpha\nbeta\n", Truncate, none, "alpha\nbeta\n"},
		{"append-existing", "two\n", Append, "one\n", "one\ntwo\n"},
		{"atomic-replace", "new\n", Atomic, "old\n", "new\n"},
		{"truncate-longer", "short\n", Truncate, "a much longer old line\n", "short\n"},
		{"empty-truncate", "", Truncate, "old\n", ""},
		{"empty-new", "", Truncate, none, ""},
		{"append-missing", "first\n", Append, none, "first\n"},
		{"append-no-newline", "two", Append, "one", "onetwo"},
		{"non-ascii", "naïve café\n日本語\n🙂\n", Truncate, none, "naïve café\n日本語\n🙂\n"},
		{"crlf", "one\r\ntwo\r\n", Truncate, none, "one\r\ntwo\r\n"},
		{"mixed-endings", "lf\ncrlf\r\ncr\rend", Truncate, none, "lf\ncrlf\r\ncr\rend"},
		{"backslashes", "C:\\temp\\new\n", Truncate, none, "C:\\temp\\new\n"},
		{"format-chars", "-n 100% %s\n", Truncate, none, "-n 100% %s\n"},
		{"atomic-new", "new\n", Atomic, none, "new\n"},
		{"atomic-empty", "", Atomic, "old\n", ""},
		{"atomic-non-ascii", "naïve café\n日本語\n🙂\n", Atomic, "old\n", "naïve café\n日本語\n🙂\n"},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			dir := t.TempDir()
			path := filepath.Join(dir, "out.txt")
			if c.before != none {
				if err := os.WriteFile(path, []byte(c.before), 0o666); err != nil {
					t.Fatal(err)
				}
			}
			if err := WriteText(path, c.text, c.mode); err != nil {
				t.Fatal(err)
			}
			got, err := os.ReadFile(path)
			if err != nil {
				t.Fatal(err)
			}
			if string(got) != c.want {
				t.Errorf("the file holds %q, want %q", got, c.want)
			}
			if n := names(t, dir); !slices.Equal(n, []string{"out.txt"}) {
				t.Errorf("the directory holds %q", n)
			}
		})
	}
}

func TestMissingDir(t *testing.T) {
	for _, mode := range []string{Truncate, Append, Atomic} {
		t.Run("missing-dir-"+mode, func(t *testing.T) {
			dir := t.TempDir()
			err := WriteText(filepath.Join(dir, "missing", "out.txt"), "x\n", mode)
			if !errors.Is(err, fs.ErrNotExist) {
				t.Errorf("err = %v, want fs.ErrNotExist", err)
			}
			if n := names(t, dir); len(n) != 0 {
				t.Errorf("the directory holds %q", n)
			}
		})
	}
}

func TestAtomicOntoDirectory(t *testing.T) {
	dir := t.TempDir()
	path := filepath.Join(dir, "out.txt")
	if err := os.Mkdir(path, 0o777); err != nil {
		t.Fatal(err)
	}
	if err := WriteText(path, "x\n", Atomic); err == nil {
		t.Fatal("no error")
	}
	if info, err := os.Stat(path); err != nil || !info.IsDir() {
		t.Errorf("out.txt is no longer a directory: %v", err)
	}
	if n := names(t, dir); !slices.Equal(n, []string{"out.txt"}) {
		t.Errorf("the directory holds %q", n)
	}
}
write_text.rsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

//! Writes a string to a file in one of three modes.

use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process;
use std::sync::atomic::{AtomicU64, Ordering};

/// The modes of [`write_text`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
    Truncate,
    Append,
    Atomic,
}

/// Writes `text` to `path`. A `&str` is UTF-8, so the bytes go to the file
/// with no change: no byte order mark and no change of the line ends.
pub fn write_text(path: &Path, text: &str, mode: Mode) -> io::Result<()> {
    match mode {
        // fs::write creates the file, or truncates it if it exists.
        Mode::Truncate => fs::write(path, text),
        Mode::Append => OpenOptions::new()
            .append(true)
            .create(true)
            .open(path)?
            .write_all(text.as_bytes()),
        Mode::Atomic => replace(path, text),
    }
}

fn replace(path: &Path, text: &str) -> io::Result<()> {
    let (tmp, mut file) = create_temp(path)?;
    let result = file
        .write_all(text.as_bytes())
        .and_then(|()| file.sync_all())
        .and_then(|()| {
            drop(file);
            fs::rename(&tmp, path)
        });
    if result.is_err() {
        let _ = fs::remove_file(&tmp);
    }
    result
}

// Makes a new file next to path. The name is in the same directory, so the
// rename does not cross a file system. create_new fails if the name exists.
fn create_temp(path: &Path) -> io::Result<(PathBuf, File)> {
    static COUNT: AtomicU64 = AtomicU64::new(0);
    let base = path.file_name().unwrap_or_default().to_string_lossy();
    loop {
        let n = COUNT.fetch_add(1, Ordering::Relaxed);
        let tmp = path.with_file_name(format!(".{base}.{}.{n}.tmp", process::id()));
        match OpenOptions::new().write(true).create_new(true).open(&tmp) {
            Ok(file) => return Ok((tmp, file)),
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
            Err(e) => return Err(e),
        }
    }
}
tests/write_text_test.rs 91 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-file/.

use algo_write_a_file::{Mode, write_text};
use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};

// A new empty directory for one test, removed when it goes out of scope.
struct TempDir(PathBuf);

impl TempDir {
    fn new() -> TempDir {
        static COUNT: AtomicU64 = AtomicU64::new(0);
        let n = COUNT.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!("write-text-{}-{n}", std::process::id()));
        fs::create_dir(&dir).unwrap();
        TempDir(dir)
    }

    fn names(&self) -> Vec<String> {
        let mut out: Vec<String> = fs::read_dir(&self.0)
            .unwrap()
            .map(|e| e.unwrap().file_name().into_string().unwrap())
            .collect();
        out.sort();
        out
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

const NON_ASCII: &str = "naïve café\n日本語\n🙂\n";

const CASES: &[(&str, &str, Mode, Option<&str>, &str)] = &[
    ("new-file", "alpha\nbeta\n", Mode::Truncate, None, "alpha\nbeta\n"),
    ("append-existing", "two\n", Mode::Append, Some("one\n"), "one\ntwo\n"),
    ("atomic-replace", "new\n", Mode::Atomic, Some("old\n"), "new\n"),
    ("truncate-longer", "short\n", Mode::Truncate, Some("a much longer old line\n"), "short\n"),
    ("empty-truncate", "", Mode::Truncate, Some("old\n"), ""),
    ("empty-new", "", Mode::Truncate, None, ""),
    ("append-missing", "first\n", Mode::Append, None, "first\n"),
    ("append-no-newline", "two", Mode::Append, Some("one"), "onetwo"),
    ("non-ascii", NON_ASCII, Mode::Truncate, None, NON_ASCII),
    ("crlf", "one\r\ntwo\r\n", Mode::Truncate, None, "one\r\ntwo\r\n"),
    ("mixed-endings", "lf\ncrlf\r\ncr\rend", Mode::Truncate, None, "lf\ncrlf\r\ncr\rend"),
    ("backslashes", "C:\\temp\\new\n", Mode::Truncate, None, "C:\\temp\\new\n"),
    ("format-chars", "-n 100% %s\n", Mode::Truncate, None, "-n 100% %s\n"),
    ("atomic-new", "new\n", Mode::Atomic, None, "new\n"),
    ("atomic-empty", "", Mode::Atomic, Some("old\n"), ""),
    ("atomic-non-ascii", NON_ASCII, Mode::Atomic, Some("old\n"), NON_ASCII),
];

#[test]
fn cases() {
    for &(name, text, mode, before, want) in CASES {
        let dir = TempDir::new();
        let path = dir.0.join("out.txt");
        if let Some(before) = before {
            fs::write(&path, before).unwrap();
        }
        write_text(&path, text, mode).unwrap_or_else(|e| panic!("{name}: {e}"));
        assert_eq!(fs::read(&path).unwrap(), want.as_bytes(), "{name}");
        assert_eq!(dir.names(), ["out.txt"], "{name}");
    }
}

#[test]
fn missing_dir() {
    for mode in [Mode::Truncate, Mode::Append, Mode::Atomic] {
        let dir = TempDir::new();
        let err = write_text(&dir.0.join("missing/out.txt"), "x\n", mode).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::NotFound, "missing-dir-{mode:?}");
        assert!(dir.names().is_empty(), "missing-dir-{mode:?}");
    }
}

#[test]
fn atomic_onto_directory() {
    let dir = TempDir::new();
    let path = dir.0.join("out.txt");
    fs::create_dir(&path).unwrap();
    assert!(write_text(&path, "x\n", Mode::Atomic).is_err());
    assert!(path.is_dir());
    assert_eq!(dir.names(), ["out.txt"]);
}
write_text.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-file/.

# write_text PATH TEXT MODE writes TEXT to PATH with no change to its bytes.
# MODE is truncate, append or atomic.
write_text() {
  local path=$1 text=$2 mode=$3 tmp
  case $mode in
    # printf '%s' writes the bytes as they are: no newline at the end, and
    # no change to a backslash, a % or a leading -n.
    truncate) printf '%s' "$text" >"$path" ;;
    append) printf '%s' "$text" >>"$path" ;;
    atomic)
      # mv onto a directory moves the file into it, so refuse a directory.
      if [ -d "$path" ]; then
        printf 'write_text: %s: is a directory\n' "$path" >&2
        return 1
      fi
      # The temporary file is in the same directory, so mv is a rename.
      tmp=$(mktemp "$path.XXXXXX") || return
      if printf '%s' "$text" >"$tmp" && mv -f "$tmp" "$path"; then
        return 0
      fi
      rm -f "$tmp"
      return 1
      ;;
    *)
      printf 'write_text: unknown mode %s\n' "$mode" >&2
      return 2
      ;;
  esac
}
test_write_text.bats 59 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-file/.

setup() {
  source "$BATS_TEST_DIRNAME/write_text.sh"
  dir=$BATS_TEST_TMPDIR/d
  mkdir "$dir"
  path=$dir/out.txt
}

# check TEXT MODE BEFORE WANT. BEFORE is "-" when no file is there.
check() {
  if [ "$3" != - ]; then
    printf '%s' "$3" >"$path"
  fi
  write_text "$path" "$1" "$2"
  printf '%s' "$4" >"$BATS_TEST_TMPDIR/want"
  cmp "$path" "$BATS_TEST_TMPDIR/want"
  [ "$(ls -A "$dir")" = out.txt ]
}

non_ascii=$'na\xc3\xafve caf\xc3\xa9\n\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\n\xf0\x9f\x99\x82\n'

@test "new-file" { check $'alpha\nbeta\n' truncate - $'alpha\nbeta\n'; }
@test "append-existing" { check $'two\n' append $'one\n' $'one\ntwo\n'; }
@test "atomic-replace" { check $'new\n' atomic $'old\n' $'new\n'; }
@test "truncate-longer" { check $'short\n' truncate $'a much longer old line\n' $'short\n'; }
@test "empty-truncate" { check '' truncate $'old\n' ''; }
@test "empty-new" { check '' truncate - ''; }
@test "append-missing" { check $'first\n' append - $'first\n'; }
@test "append-no-newline" { check two append one onetwo; }
@test "non-ascii" { check "$non_ascii" truncate - "$non_ascii"; }
@test "crlf" { check $'one\r\ntwo\r\n' truncate - $'one\r\ntwo\r\n'; }
@test "mixed-endings" { check $'lf\ncrlf\r\ncr\rend' truncate - $'lf\ncrlf\r\ncr\rend'; }
@test "backslashes" { check $'C:\\temp\\new\n' truncate - $'C:\\temp\\new\n'; }
@test "format-chars" { check $'-n 100% %s\n' truncate - $'-n 100% %s\n'; }
@test "atomic-new" { check $'new\n' atomic - $'new\n'; }
@test "atomic-empty" { check '' atomic $'old\n' ''; }
@test "atomic-non-ascii" { check "$non_ascii" atomic $'old\n' "$non_ascii"; }

missing() {
  run write_text "$dir/missing/out.txt" $'x\n' "$1"
  [ "$status" -ne 0 ]
  [ -z "$(ls -A "$dir")" ]
}

@test "missing-dir-truncate" { missing truncate; }
@test "missing-dir-append" { missing append; }
@test "missing-dir-atomic" { missing atomic; }

@test "atomic-onto-directory" {
  mkdir "$path"
  run write_text "$path" $'x\n' atomic
  [ "$status" -ne 0 ]
  [ -d "$path" ]
  [ -z "$(ls -A "$path")" ]
  [ "$(ls -A "$dir")" = out.txt ]
}

References

  1. The Open Group, POSIX.1-2024, rename, Description, Errors (EISDIR, EXDEV)
  2. The Open Group, POSIX.1-2024, mkdtemp, mkstemp, Description
  3. The Open Group, POSIX.1-2024, fsync, Description
  4. The Open Group, POSIX.1-2024, mv, Description, second synopsis form
  5. Linux man-pages, fsync(2), Description
  6. Linux man-pages, close(2), Caveats, Dealing with error returns from close()
  7. The Python Standard Library, Built-in Functions, open(), mode, encoding, newline
  8. The Python Standard Library, tempfile, mkstemp
  9. The Python Standard Library, os, Miscellaneous operating system interfaces, os.replace, os.fsync
  10. Node.js documentation, File system, fsPromises.writeFile, filehandle.sync, fsPromises.rename, File system flags
  11. Java SE 25 API, java.nio.file.Files, writeString(Path, CharSequence, Charset, OpenOption...), move(Path, Path, CopyOption...), createTempFile(Path, String, String, FileAttribute...)
  12. Java SE 25 API, java.nio.channels.FileChannel, force(boolean)
  13. .NET API reference, File.WriteAllText, WriteAllText(String, String), Remarks
  14. .NET API reference, Encoding.UTF8, Remarks
  15. .NET API reference, File.Move, Move(String, String, Boolean), Remarks
  16. .NET API reference, FileStream.Flush, Flush(Boolean), Remarks
  17. Go standard library, package os, WriteFile, OpenFile, CreateTemp, File.Sync, Rename
  18. The Rust Standard Library, std::fs::write
  19. The Rust Standard Library, std::fs::OpenOptions, append, create, create_new
  20. The Rust Standard Library, std::fs::File, sync_all
  21. The Rust Standard Library, std::fs::rename, Platform-specific behavior, Errors
  22. cppreference.com, fopen, File access flags
  23. cppreference.com, std::filesystem::rename
  24. GNU Bash Reference Manual, Bash Builtin Commands, 4.2, echo, printf
  25. GNU Bash Reference Manual, Redirections, 3.6.2 Redirecting Output, 3.6.3 Appending Redirected Output

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
  • no problem that the node solves has a contract with shared cases (09.2)
Code (cpp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (csharp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (go)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (java)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (javascript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (python)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (rust)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (typescript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source

The native tests pass in 9 of 10 languages in this build.