Programming Search⌘K

Taskadvanced

Sync a file to disk

Also called fsync, fdatasync, flush a file to disk, durable write, sync_all, force a file to disk.

Write a file and do not return until its data is on the storage device, with fsync on the file and then on its directory, so that the data and the name stay after a crash or a power loss.

Task

Write a string to a file, and do not return until the data is on the storage device. The entry is write_synced(path, text). It creates or truncates the file, writes all the bytes of text as UTF-8, and then:

  1. empties the buffer of the language into the kernel;
  2. calls fsync on the file, or the equal call of the language;
  3. closes the file, and checks the error of the close;
  4. calls fsync on the directory that holds the file.

A write that returns puts the data in the memory of the kernel, not on the disk. The kernel writes it later. When the machine loses power first, the data is lost, and a new file can be lost with its name. POSIX says that fsync "is intended to force a physical write of data from the buffer cache, and to assure that after a system crash or other failure that all data up to the time of the fsync () call is recorded on the disk."

The sync of the file does not save its name. Linux says: "Calling fsync () does not necessarily ensure that the entry in the directory containing the file has also reached disk. For that an explicit fsync () on a file descriptor for the directory is also needed." So step 4 is necessary for a new file.

Report an error when the directory of path does not exist, and when path is a directory. Report each error of the write, the sync and the close. SQL, regular expressions, HTML and CSS do not apply, because they do not write files.

Solutions

  • Python. f.flush(), then os.fsync(f.fileno()). Python says: "If you’re starting with a buffered Python file object f , first do f.flush() , and then do os.fsync(f.fileno()) , to ensure that all internal buffers associated with f are written to disk." On Unix, os.fsync "calls the native fsync() function". For the directory, the solution opens it with os.open(dir, os.O_RDONLY) and calls os.fsync on that descriptor. On macOS it first tries fcntl(fd, F_FULLFSYNC) (see Pitfalls).
  • JavaScript and TypeScript (Node.js). fs.openSync, fs.writeFileSync(fd, text), fs.fsyncSync(fd) and fs.closeSync(fd). The promise API has filehandle.sync(), which will "Request that all data for the open file descriptor is flushed to the storage device." A directory opens with the flag "r", and fsyncSync works on it on Linux and macOS.
  • Java. FileChannel.force(true). Java says: "If this channel's file resides on a local storage device then when this method returns it is guaranteed that all changes made to the file since this channel was created, or since this method was last invoked, will have been written to that device." The argument false asks only for the content, as fdatasync does. Java has no call for a directory, but on Linux and macOS FileChannel.open(dir, READ) opens it, and force syncs it.
  • C#. FileStream.Flush(true). It is for when "you want to ensure that all buffered data in intermediate file buffers is written to disk". .NET cannot open a directory as a stream, so the solution calls open, fsync and close of the C library through DllImport for the directory.
  • Go. (*os.File).Sync. Go says that Sync "commits the current contents of the file to stable storage." An *os.File has no buffer, so no flush comes first. For the directory, os.Open(dir) and then Sync.
  • Rust. File::sync_all, which "Attempts to sync all OS-internal file content and metadata to disk." It also gives the error that a drop of the file loses: it "can be used to handle errors that would otherwise only be caught when the File is closed, as dropping a File will ignore all errors." For the directory, File::open(dir)?.sync_all().
  • C. open, a loop of write, fsync, close, and then open(dir, O_RDONLY | O_DIRECTORY) and fsync on the directory. On macOS, fcntl(fd, F_FULLFSYNC) comes first.
  • C++. std::ofstream::flush does not reach the device. It "Writes uncommitted changes to the underlying output sequence", which is the kernel. The standard library has no sync call, so the solution uses the POSIX calls, as in C, and reports errors through std::error_code.
  • Bash. GNU sync syncs the files that it is given: sync -- "$path" && sync -- "$dir". The sync of macOS and BSD takes no file, so there the solution syncs all file systems. Linux says that sync "causes all pending modifications to filesystem metadata and cached file data to be written to the underlying filesystems."

In Python, the order of the steps is: write, flush, sync the file, close, sync the directory. The example prints each sync:

import os
import tempfile


def sync_directory(directory):
    fd = os.open(directory, os.O_RDONLY)
    try:
        os.fsync(fd)
    finally:
        os.close(fd)


def write_synced(path, text):
    with open(path, "w", encoding="utf-8", newline="") as f:
        f.write(text)
        f.flush()
        os.fsync(f.fileno())
    sync_directory(os.path.dirname(os.path.abspath(path)))


real_fsync = os.fsync


def show_fsync(fd):
    kind = "directory" if os.path.isdir(f"/dev/fd/{fd}") else "file"
    print("fsync of the", kind)
    real_fsync(fd)


os.fsync = show_fsync
os.chdir(tempfile.mkdtemp())
write_synced("orders.txt", "order 42: paid\n")
with open("orders.txt", encoding="utf-8") as f:
    print("orders.txt holds:", f.read(), end="")
Output
fsync of the file
fsync of the directory
orders.txt holds: order 42: paid

In Go:

package main

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

func writeSynced(path, text string) error {
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
	if err != nil {
		return err
	}
	if _, err := f.WriteString(text); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	d, err := os.Open(filepath.Dir(path))
	if err != nil {
		return err
	}
	defer d.Close()
	return d.Sync()
}

func main() {
	work, err := os.MkdirTemp("", "sync-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(work)
	path := filepath.Join(work, "orders.txt")
	if err := writeSynced(path, "order 42: paid\n"); err != nil {
		panic(err)
	}
	b, _ := os.ReadFile(path)
	fmt.Printf("orders.txt holds: %s", b)
	fmt.Println("error for a missing directory:", writeSynced(filepath.Join(work, "missing", "x.txt"), "x") != nil)
}
Output
orders.txt holds: order 42: paid
error for a missing directory: true

Edge cases

The cases are in cases/basic.jsonl, cases/edge.jsonl and cases/errors.jsonl. Each test runs in a new, empty directory, and the file is out.txt.

  • new-file, replace-longer and many-lines: the file holds the bytes of text and no old byte, and it is the only file in the directory.
  • empty-replace and empty-new: an empty text gives an empty file. The sync still runs, because the truncation is a change too.
  • no-final-newline, non-ascii and crlf: the bytes stay as they are. A solution must not add a newline or change \r\n.
  • Errors: missing/out.txt gives not-found, and no file is made. When out.txt is a directory, the solution gives is-a-directory, and the directory stays.

A test cannot cut the power, so the cases check only the content. The native tests also call the directory sync alone, and the Python test checks the order: the file first, then its directory, and an error of fsync comes back to the caller.

Pitfalls

  • A flush is not a sync. A flush moves the data from the buffer of the language to the kernel. Python flush will "Flush the write buffers of the stream if applicable." The data is then in memory, not on the disk. A sync without a flush first also fails: the data is still in the buffer of the language, so fsync does not see it.

This code runs but gives a wrong answer on purpose.

import os
import tempfile

os.chdir(tempfile.mkdtemp())
f = open("orders.txt", "w", encoding="utf-8")
f.write("order 42: paid\n")
os.fsync(f.fileno())  # no f.flush() first
with open("orders.txt", encoding="utf-8") as g:
    print("the kernel had at the fsync:", repr(g.read()))
f.close()
Output
the kernel had at the fsync: ''
  • No sync of the directory. After a crash, a new file that had a sync can be missing, because its name was not on the disk. POSIX says: "An application that modifies a directory, for example, by creating a file in the directory, can invoke fsync () on the directory to ensure that the directory's entries and file attributes are synchronized." A rename also changes a directory, so Write a file atomically syncs the directory after the rename.
  • Do not try the sync again after an error. When fsync fails, the kernel can mark the data clean and drop it. The PostgreSQL wiki says that on Linux "you still only get the error once (so retrying fsync() is not OK)". After the problems of 2018, "PostgreSQL will now PANIC on fsync() failure." Treat a failed sync as lost data: report it, and write the data again from a copy that you trust.
  • macOS and the cache of the drive. On macOS, fsync sends the data to the drive, but the drive can keep the data in its cache for some time, and "it may be written in an out-of-order sequence." For a stronger rule, "Mac OS X provides the F_FULLFSYNC fcntl. The F_FULLFSYNC fcntl asks the drive to flush all buffered data to permanent storage." The Python and C solutions use it. The other languages call only fsync.
  • fdatasync and the size of the file. fdatasync (Python os.fdatasync, Rust sync_data, Java force(false)) does not sync all the metadata, so it is faster. Linux says that it "does not flush modified metadata unless that metadata is needed in order to allow a subsequent data retrieval to be correctly handled", and "a change to the file size ( st_size , as made by say ftruncate(2) ), would require a metadata flush". Rust says that sync_data "might not synchronize file metadata to the filesystem".
  • The promise is weak. The POSIX rationale of fsync says: "It is explicitly intended that a null implementation is permitted." A file system, a virtual machine or a drive can say that the data is on the disk when it is not. A study of file systems found that application update protocols depend on "subtle behaviors of the underlying file system", and the study used them to find crash bugs in eleven applications.7 Test the full protocol of a program on the file system that it uses.
  • A sync is slow. The call "blocks until the device reports that the transfer has completed". A program that syncs after each small write can be many times slower. Put many changes in one file write, and sync once for each group of changes.
  • An error can come from another descriptor. Linux says of EIO: "This error may relate to data written to some other file descriptor on the same file." So a sync can fail for data that another part of the program wrote.

Code

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

write_synced.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sync-a-file-to-disk/.

import os
import sys


def _sync(fd: int) -> None:
    # On macOS, fsync sends the data to the drive, but the drive can keep it
    # in its cache. F_FULLFSYNC asks the drive to write its cache too. Some
    # file systems do not support it, so fsync is the fallback.
    if sys.platform == "darwin":
        import fcntl

        try:
            fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
            return
        except OSError:
            pass
    os.fsync(fd)


def sync_directory(directory: str | os.PathLike[str]) -> None:
    """Sync the entries of a directory, so that a new name in it is on disk."""
    fd = os.open(directory, os.O_RDONLY)
    try:
        os.fsync(fd)
    finally:
        os.close(fd)


def write_synced(path: str | os.PathLike[str], text: str) -> None:
    """Write text to path as UTF-8, and return when it is on the disk."""
    # newline="" turns off the change of "\n" to os.linesep.
    with open(path, "w", encoding="utf-8", newline="") as f:
        f.write(text)
        f.flush()  # from the buffer of Python to the kernel
        _sync(f.fileno())  # from the kernel to the device
    # The close of the with statement raises its error, if there is one.
    sync_directory(os.path.dirname(os.path.abspath(path)))
test_write_synced.py 71 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sync-a-file-to-disk/.

import os
from pathlib import Path

import pytest

import write_synced as ws

# name: (text, the file before the call or None)
CASES = {
    "new-file": ("alpha\nbeta\n", None),
    "replace-longer": ("short\n", "a much longer old line\n"),
    "many-lines": ("one\ntwo\nthree\nfour\n", None),
    "empty-replace": ("", "old\n"),
    "empty-new": ("", None),
    "no-final-newline": ("last line", None),
    "non-ascii": ("naïve café\n日本語\n🙂\n", None),
    "crlf": ("one\r\ntwo\r\n", None),
}


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
    text, before = CASES[name]
    path = tmp_path / "out.txt"
    if before is not None:
        path.write_bytes(before.encode())
    ws.write_synced(path, text)
    assert path.read_bytes() == text.encode()
    assert os.listdir(tmp_path) == ["out.txt"]


def test_syncs_the_file_and_the_directory(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    synced = []
    real = os.fsync

    def spy(fd: int) -> None:
        synced.append(os.path.isdir(f"/dev/fd/{fd}"))
        real(fd)

    monkeypatch.setattr(os, "fsync", spy)
    monkeypatch.setattr(ws.sys, "platform", "linux")  # take the fsync path on macOS too
    ws.write_synced(tmp_path / "out.txt", "x\n")
    # First the file, then its directory.
    assert synced == [False, True]


def test_sync_error_is_raised(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    def fail(fd: int) -> None:
        raise OSError(5, "Input/output error")

    monkeypatch.setattr(os, "fsync", fail)
    monkeypatch.setattr(ws.sys, "platform", "linux")
    with pytest.raises(OSError):
        ws.write_synced(tmp_path / "out.txt", "x\n")


def test_missing_directory(tmp_path: Path) -> None:
    with pytest.raises(FileNotFoundError):
        ws.write_synced(tmp_path / "missing" / "out.txt", "x\n")
    assert os.listdir(tmp_path) == []


def test_onto_directory(tmp_path: Path) -> None:
    path = tmp_path / "out.txt"
    path.mkdir()
    with pytest.raises(IsADirectoryError):
        ws.write_synced(path, "x\n")
    assert path.is_dir()
write_synced.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

#include "write_synced.hpp"

#include <fcntl.h>
#include <unistd.h>

#include <cerrno>

namespace fs = std::filesystem;

namespace files {

namespace {

std::error_code last_error() { return {errno, std::generic_category()}; }

// fail sets ec from errno, then closes fd.
void fail(int fd, std::error_code& ec) {
    ec = last_error();
    ::close(fd);
}

}  // namespace

void sync_directory(const fs::path& dir, std::error_code& ec) {
    ec.clear();
    int fd = ::open(dir.c_str(), O_RDONLY | O_DIRECTORY);
    if (fd < 0) {
        ec = last_error();
        return;
    }
    if (::fsync(fd) != 0) {
        fail(fd, ec);
        return;
    }
    if (::close(fd) != 0) ec = last_error();
}

void write_synced(const fs::path& path, std::string_view text, std::error_code& ec) {
    ec.clear();
    int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) {
        ec = last_error();
        return;
    }
    // write can write fewer bytes than asked, so it runs in a loop.
    for (std::size_t done = 0; done < text.size();) {
        ssize_t n = ::write(fd, text.data() + done, text.size() - done);
        if (n < 0) {
            if (errno == EINTR) continue;
            fail(fd, ec);
            return;
        }
        done += static_cast<std::size_t>(n);
    }
    if (::fsync(fd) != 0) {
        fail(fd, ec);
        return;
    }
    if (::close(fd) != 0) {
        ec = last_error();
        return;
    }
    fs::path abs = fs::absolute(path, ec);
    if (ec) return;
    sync_directory(abs.parent_path(), ec);
}

}  // namespace files
write_synced.hpp 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

#pragma once

#include <filesystem>
#include <string_view>
#include <system_error>

namespace files {

// Syncs the entries of the directory dir, so that a new name in it is on
// disk. On an error it sets ec.
void sync_directory(const std::filesystem::path& dir, std::error_code& ec);

// Writes text to path, syncs the file, closes it, and syncs the directory of
// path. std::ofstream has no call that syncs to the device, so this uses the
// POSIX calls open, write, fsync and close. On an error it sets ec, for example
// to std::errc::no_such_file_or_directory or std::errc::is_a_directory.
void write_synced(const std::filesystem::path& path, std::string_view text, std::error_code& ec);

}  // namespace files
test_write_synced.cpp 84 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <optional>
#include <string>
#include <system_error>

#include "write_synced.hpp"

namespace fs = std::filesystem;

namespace {

const fs::path dir = "sync_tree";
int failures = 0;

void expect(bool ok, const std::string& what) {
    if (!ok) {
        std::fprintf(stderr, "%s\n", what.c_str());
        ++failures;
    }
}

void fresh() {
    fs::remove_all(dir);
    fs::create_directories(dir);
}

int count(const fs::path& d) { return static_cast<int>(std::distance(fs::directory_iterator(d), {})); }

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

}  // namespace

int main() {
    struct Case {
        const char* name;
        std::string text;
        std::optional<std::string> before;
    };
    const Case cases[] = {
        {"new-file", "alpha\nbeta\n", std::nullopt},
        {"replace-longer", "short\n", "a much longer old line\n"},
        {"many-lines", "one\ntwo\nthree\nfour\n", std::nullopt},
        {"empty-replace", "", "old\n"},
        {"empty-new", "", std::nullopt},
        {"no-final-newline", "last line", std::nullopt},
        {"non-ascii", "na\xc3\xafve caf\xc3\xa9\n\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e\n\xf0\x9f\x99\x82\n", std::nullopt},
        {"crlf", "one\r\ntwo\r\n", std::nullopt},
    };
    const fs::path path = dir / "out.txt";
    std::error_code ec;
    for (const Case& c : cases) {
        fresh();
        if (c.before) std::ofstream(path, std::ios::binary) << *c.before;
        files::write_synced(path, c.text, ec);
        expect(!ec && slurp(path) == c.text && count(dir) == 1, c.name);
    }

    fresh();
    files::sync_directory(dir, ec);
    expect(!ec, "sync-directory");

    fresh();
    files::write_synced(dir / "missing" / "out.txt", "x\n", ec);
    expect(ec == std::errc::no_such_file_or_directory && count(dir) == 0, "missing-directory");

    fresh();
    fs::create_directory(path);
    files::write_synced(path, "x\n", ec);
    expect(ec == std::errc::is_a_directory && fs::is_directory(path), "onto-directory");

    fs::remove_all(dir);
    if (failures != 0) return 1;
    std::printf("ok\n");
    return 0;
}
WriteSynced.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.READ;
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
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.Path;

/** Writes a file and returns when its data is on the storage device. */
public final class WriteSynced {
  private WriteSynced() {}

  /** Writes text to path as UTF-8, and syncs the file and its directory. */
  public static void writeSynced(Path path, String text) throws IOException {
    try (FileChannel ch = FileChannel.open(path, WRITE, CREATE, TRUNCATE_EXISTING)) {
      ByteBuffer buf = ByteBuffer.wrap(text.getBytes(StandardCharsets.UTF_8));
      while (buf.hasRemaining()) {
        ch.write(buf);
      }
      // true: sync the metadata too, as fsync does. false is like fdatasync.
      ch.force(true);
    }
    syncDirectory(path.toAbsolutePath().getParent());
  }

  /**
   * Syncs the entries of a directory, so that a new name in it is on disk. Java
   * has no call for it, but on Linux and macOS a directory opens for reading as
   * a channel, and force calls fsync on it.
   */
  public static void syncDirectory(Path dir) throws IOException {
    try (FileChannel ch = FileChannel.open(dir, READ)) {
      ch.force(true);
    }
  }
}
WriteSyncedTest.java 76 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

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.FileSystemException;
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.MethodSource;

class WriteSyncedTest {
  @TempDir Path dir;

  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("new-file", "alpha\nbeta\n", null),
        Arguments.of("replace-longer", "short\n", "a much longer old line\n"),
        Arguments.of("many-lines", "one\ntwo\nthree\nfour\n", null),
        Arguments.of("empty-replace", "", "old\n"),
        Arguments.of("empty-new", "", null),
        Arguments.of("no-final-newline", "last line", null),
        Arguments.of("non-ascii", "naïve café\n日本語\n🙂\n", null),
        Arguments.of("crlf", "one\r\ntwo\r\n", null));
  }

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

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void writes(String name, String text, String before) throws IOException {
    Path path = dir.resolve("out.txt");
    if (before != null) {
      Files.write(path, before.getBytes(StandardCharsets.UTF_8));
    }
    WriteSynced.writeSynced(path, text);
    assertArrayEquals(text.getBytes(StandardCharsets.UTF_8), Files.readAllBytes(path), name);
    assertEquals(List.of("out.txt"), names());
  }

  @Test
  void syncsADirectory() throws IOException {
    WriteSynced.syncDirectory(dir);
  }

  @Test
  void missingDirectory() throws IOException {
    assertThrows(
        NoSuchFileException.class,
        () -> WriteSynced.writeSynced(dir.resolve("missing").resolve("out.txt"), "x\n"));
    assertEquals(List.of(), names());
  }

  @Test
  void ontoDirectory() throws IOException {
    Path path = dir.resolve("out.txt");
    Files.createDirectory(path);
    assertThrows(FileSystemException.class, () -> WriteSynced.writeSynced(path, "x\n"));
    assertTrue(Files.isDirectory(path));
  }
}
write_synced.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

#define _POSIX_C_SOURCE 200809L
#define _DARWIN_C_SOURCE // F_FULLFSYNC on macOS

#include "write_synced.h"

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

// sync_fd sends the data of fd to the device. On macOS, fsync leaves the data
// in the cache of the drive, and F_FULLFSYNC asks the drive to write it. Some
// file systems do not support F_FULLFSYNC, so fsync is the fallback.
static int sync_fd(int fd) {
#ifdef F_FULLFSYNC
    if (fcntl(fd, F_FULLFSYNC) == 0) return 0;
#endif
    return fsync(fd);
}

int sync_directory(const char *dir) {
    int fd = open(dir, O_RDONLY | O_DIRECTORY);
    if (fd < 0) return -1;
    if (fsync(fd) != 0) {
        int e = errno;
        close(fd);
        errno = e;
        return -1;
    }
    return close(fd);
}

int write_synced(const char *path, const char *text, size_t len) {
    int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) return -1;
    // write can write fewer bytes than asked, so it runs in a loop.
    for (size_t done = 0; done < len;) {
        ssize_t n = write(fd, text + done, len - done);
        if (n < 0) {
            if (errno == EINTR) continue;
            int e = errno;
            close(fd);
            errno = e;
            return -1;
        }
        done += (size_t)n;
    }
    if (sync_fd(fd) != 0) {
        int e = errno;
        close(fd);
        errno = e;
        return -1;
    }
    if (close(fd) != 0) return -1;

    // The directory of path: the part before the last slash, or ".".
    const char *slash = strrchr(path, '/');
    if (slash == NULL) return sync_directory(".");
    if (slash == path) return sync_directory("/");
    size_t n = (size_t)(slash - path);
    char *dir = malloc(n + 1);
    if (dir == NULL) return -1;
    memcpy(dir, path, n);
    dir[n] = '\0';
    int rc = sync_directory(dir);
    int e = errno;
    free(dir);
    errno = e;
    return rc;
}
write_synced.h 16 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

#ifndef WRITE_SYNCED_H
#define WRITE_SYNCED_H

#include <stddef.h>

// Syncs the entries of the directory dir. It returns 0, or -1 with errno set.
int sync_directory(const char *dir);

// Writes the len bytes of text to path, syncs the file, closes it, and syncs
// the directory of path. It returns 0, or -1 with errno set.
int write_synced(const char *path, const char *text, size_t len);

#endif
test_write_synced.c 99 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

#define _POSIX_C_SOURCE 200809L

#include "write_synced.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"

static const char *dir = "sync_tree";
static const char *path = "sync_tree/out.txt";
static int failures = 0;

static void expect(int ok, const char *what) {
    if (!ok) {
        fprintf(stderr, "%s\n", what);
        failures++;
    }
}

static void fresh(void) {
    if (system("rm -rf sync_tree && mkdir sync_tree") != 0) exit(2);
}

// count gives the number of entries in d, without . and ..
static int count(const char *d) {
    DIR *dp = opendir(d);
    if (dp == NULL) exit(2);
    int n = 0;
    struct dirent *e;
    while ((e = readdir(dp)) != NULL)
        if (strcmp(e->d_name, ".") != 0 && strcmp(e->d_name, "..") != 0) n++;
    closedir(dp);
    return n;
}

// equal checks that the file at p holds the bytes of want.
static int equal(const char *p, const char *want) {
    FILE *f = fopen(p, "rb");
    if (f == NULL) return 0;
    char buf[256];
    size_t n = fread(buf, 1, sizeof buf, f);
    fclose(f);
    return n == strlen(want) && memcmp(buf, want, n) == 0;
}

int main(void) {
    static const struct {
        const char *name, *text, *before;
    } cases[] = {
        {"new-file", "alpha\nbeta\n", NULL},
        {"replace-longer", "short\n", "a much longer old line\n"},
        {"many-lines", "one\ntwo\nthree\nfour\n", NULL},
        {"empty-replace", "", "old\n"},
        {"empty-new", "", NULL},
        {"no-final-newline", "last line", NULL},
        {"non-ascii", NON_ASCII, NULL},
        {"crlf", "one\r\ntwo\r\n", NULL},
    };
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        fresh();
        if (cases[i].before != NULL) {
            FILE *f = fopen(path, "wb");
            if (f == NULL) return 2;
            fputs(cases[i].before, f);
            fclose(f);
        }
        int rc = write_synced(path, cases[i].text, strlen(cases[i].text));
        expect(rc == 0 && equal(path, cases[i].text), cases[i].name);
        expect(count(dir) == 1, cases[i].name);
    }

    fresh();
    expect(sync_directory(dir) == 0, "sync-directory");

    fresh();
    errno = 0;
    expect(write_synced("sync_tree/missing/out.txt", "x\n", 2) == -1 && errno == ENOENT, "missing-directory");
    expect(count(dir) == 0, "missing-directory: no file");

    fresh();
    mkdir(path, 0755);
    errno = 0;
    expect(write_synced(path, "x\n", 2) == -1 && errno == EISDIR, "onto-directory");
    struct stat st;
    expect(stat(path, &st) == 0 && S_ISDIR(st.st_mode), "onto-directory: the directory stays");

    if (system("rm -rf sync_tree") != 0) return 2;
    if (failures == 0) printf("all tests pass\n");
    return failures == 0 ? 0 : 1;
}
WriteSynced.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;

// FileStream.Flush(true) syncs a file. .NET cannot open a directory as a
// stream, so SyncDirectory calls open, fsync and close of the C library.
[UnsupportedOSPlatform("windows")]
public static class WriteSynced
{
    [DllImport("libc", EntryPoint = "open", SetLastError = true)]
    private static extern int Open(string path, int flags);

    [DllImport("libc", EntryPoint = "fsync", SetLastError = true)]
    private static extern int Fsync(int fd);

    [DllImport("libc", EntryPoint = "close", SetLastError = true)]
    private static extern int Close(int fd);

    private const int ORdOnly = 0;

    // Syncs the entries of dir, so that a new name in it is on disk.
    public static void SyncDirectory(string dir)
    {
        int fd = Open(dir, ORdOnly);
        if (fd < 0)
        {
            throw new IOException($"open {dir}", new Win32Exception(Marshal.GetLastPInvokeError()));
        }
        int rc = Fsync(fd);
        int err = Marshal.GetLastPInvokeError();
        Close(fd);
        if (rc != 0)
        {
            throw new IOException($"fsync {dir}", new Win32Exception(err));
        }
    }

    // Writes text to path as UTF-8, syncs the file, closes it, and syncs the
    // directory of path.
    public static void Write(string path, string text)
    {
        using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            byte[] bytes = new UTF8Encoding(false).GetBytes(text);
            fs.Write(bytes);
            // true: write the buffer of the stream, then sync the file.
            fs.Flush(true);
        }
        SyncDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
    }
}
WriteSyncedTests.cs 60 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

using System.Runtime.Versioning;
using System.Text;
using Xunit;

[UnsupportedOSPlatform("windows")]
public sealed class WriteSyncedTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("sync-file-").FullName;

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

    public static TheoryData<string, string, string?> Cases => new()
    {
        { "new-file", "alpha\nbeta\n", null },
        { "replace-longer", "short\n", "a much longer old line\n" },
        { "many-lines", "one\ntwo\nthree\nfour\n", null },
        { "empty-replace", "", "old\n" },
        { "empty-new", "", null },
        { "no-final-newline", "last line", null },
        { "non-ascii", "naïve café\n日本語\n🙂\n", null },
        { "crlf", "one\r\ntwo\r\n", null },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Writes(string name, string text, string? before)
    {
        string path = Path.Combine(dir, "out.txt");
        if (before != null)
        {
            File.WriteAllText(path, before);
        }
        WriteSynced.Write(path, text);
        Assert.Equal(Encoding.UTF8.GetBytes(text), File.ReadAllBytes(path));
        Assert.Equal(new[] { "out.txt" }, Directory.GetFileSystemEntries(dir).Select(Path.GetFileName));
        Assert.True(name.Length > 0);
    }

    [Fact]
    public void SyncsADirectory() => WriteSynced.SyncDirectory(dir);

    [Fact]
    public void MissingDirectory()
    {
        Assert.Throws<DirectoryNotFoundException>(() => WriteSynced.Write(Path.Combine(dir, "missing", "out.txt"), "x\n"));
        Assert.Empty(Directory.GetFileSystemEntries(dir));
    }

    [Fact]
    public void OntoDirectory()
    {
        string path = Path.Combine(dir, "out.txt");
        Directory.CreateDirectory(path);
        Assert.Throws<UnauthorizedAccessException>(() => WriteSynced.Write(path, "x\n"));
        Assert.True(Directory.Exists(path));
    }
}
writeSynced.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

import { closeSync, fsyncSync, openSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";

/**
 * Syncs the entries of a directory, so that a new name in it is on disk.
 * @param {string} dir
 */
export function syncDirectory(dir) {
  const fd = openSync(dir, "r");
  try {
    fsyncSync(fd);
  } finally {
    closeSync(fd);
  }
}

/**
 * Writes text to file as UTF-8, and returns when it is on the disk.
 * @param {string} file
 * @param {string} text
 */
export function writeSynced(file, text) {
  // The flag "w" creates or truncates the file.
  const fd = openSync(file, "w");
  try {
    // With a descriptor, writeFileSync writes all the bytes, with no buffer
    // in Node.js, so fsync sees all of them.
    writeFileSync(fd, text, "utf8");
    fsyncSync(fd);
  } finally {
    closeSync(fd);
  }
  syncDirectory(dirname(resolve(file)));
}
writeSynced.test.js 61 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";

import { syncDirectory, writeSynced } from "./writeSynced.js";

// [case, text, the file before the call or null]
const cases = [
  ["new-file", "alpha\nbeta\n", null],
  ["replace-longer", "short\n", "a much longer old line\n"],
  ["many-lines", "one\ntwo\nthree\nfour\n", null],
  ["empty-replace", "", "old\n"],
  ["empty-new", "", null],
  ["no-final-newline", "last line", null],
  ["non-ascii", "naïve café\n日本語\n🙂\n", null],
  ["crlf", "one\r\ntwo\r\n", null],
];

function withDir(fn) {
  const dir = mkdtempSync(join(tmpdir(), "sync-"));
  try {
    fn(dir);
  } finally {
    rmSync(dir, { recursive: true, force: true });
  }
}

for (const [name, text, before] of cases) {
  test(name, () =>
    withDir((dir) => {
      const file = join(dir, "out.txt");
      if (before !== null) writeFileSync(file, before);
      writeSynced(file, text);
      assert.deepEqual(readFileSync(file), Buffer.from(text, "utf8"));
      assert.deepEqual(readdirSync(dir), ["out.txt"]);
    }),
  );
}

test("sync-directory", () => withDir((dir) => syncDirectory(dir)));

test("missing-directory", () =>
  withDir((dir) => {
    assert.throws(() => writeSynced(join(dir, "missing", "out.txt"), "x\n"), { code: "ENOENT" });
    assert.deepEqual(readdirSync(dir), []);
  }),
);

test("onto-directory", () =>
  withDir((dir) => {
    const file = join(dir, "out.txt");
    mkdirSync(file);
    assert.throws(() => writeSynced(file, "x\n"), { code: "EISDIR" });
    assert.ok(statSync(file).isDirectory());
  }),
);
writeSynced.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

import { closeSync, fsyncSync, openSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";

// Syncs the entries of a directory, so that a new name in it is on disk.
export function syncDirectory(dir: string): void {
  const fd = openSync(dir, "r");
  try {
    fsyncSync(fd);
  } finally {
    closeSync(fd);
  }
}

// Writes text to file as UTF-8, and returns when it is on the disk.
export function writeSynced(file: string, text: string): void {
  // The flag "w" creates or truncates the file.
  const fd = openSync(file, "w");
  try {
    // With a descriptor, writeFileSync writes all the bytes, with no buffer
    // in Node.js, so fsync sees all of them.
    writeFileSync(fd, text, "utf8");
    fsyncSync(fd);
  } finally {
    closeSync(fd);
  }
  syncDirectory(dirname(resolve(file)));
}
writeSynced.test.ts 61 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";

import { syncDirectory, writeSynced } from "./writeSynced.ts";

// [case, text, the file before the call or null]
const cases: [string, string, string | null][] = [
  ["new-file", "alpha\nbeta\n", null],
  ["replace-longer", "short\n", "a much longer old line\n"],
  ["many-lines", "one\ntwo\nthree\nfour\n", null],
  ["empty-replace", "", "old\n"],
  ["empty-new", "", null],
  ["no-final-newline", "last line", null],
  ["non-ascii", "naïve café\n日本語\n🙂\n", null],
  ["crlf", "one\r\ntwo\r\n", null],
];

function withDir(fn: (dir: string) => void): void {
  const dir = mkdtempSync(join(tmpdir(), "sync-"));
  try {
    fn(dir);
  } finally {
    rmSync(dir, { recursive: true, force: true });
  }
}

for (const [name, text, before] of cases) {
  test(name, () =>
    withDir((dir) => {
      const file = join(dir, "out.txt");
      if (before !== null) writeFileSync(file, before);
      writeSynced(file, text);
      assert.deepEqual(readFileSync(file), Buffer.from(text, "utf8"));
      assert.deepEqual(readdirSync(dir), ["out.txt"]);
    }),
  );
}

test("sync-directory", () => withDir((dir) => syncDirectory(dir)));

test("missing-directory", () =>
  withDir((dir) => {
    assert.throws(() => writeSynced(join(dir, "missing", "out.txt"), "x\n"), { code: "ENOENT" });
    assert.deepEqual(readdirSync(dir), []);
  }),
);

test("onto-directory", () =>
  withDir((dir) => {
    const file = join(dir, "out.txt");
    mkdirSync(file);
    assert.throws(() => writeSynced(file, "x\n"), { code: "EISDIR" });
    assert.ok(statSync(file).isDirectory());
  }),
);
write_synced.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

// Package syncfile writes a file and returns when its data is on the disk.
package syncfile

import (
	"os"
	"path/filepath"
)

// SyncDirectory syncs the entries of dir, so that a new name in it is on disk.
func SyncDirectory(dir string) error {
	d, err := os.Open(dir)
	if err != nil {
		return err
	}
	if err := d.Sync(); err != nil {
		d.Close()
		return err
	}
	return d.Close()
}

// WriteSynced writes text to path, syncs the file, closes it, and syncs the
// directory of path. Each step returns its error.
func WriteSynced(path, text string) error {
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
	if err != nil {
		return err
	}
	// An *os.File has no buffer: Write gives the bytes to the kernel.
	if _, err := f.WriteString(text); err != nil {
		f.Close()
		return err
	}
	if err := f.Sync(); err != nil {
		f.Close()
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	abs, err := filepath.Abs(path)
	if err != nil {
		return err
	}
	return SyncDirectory(filepath.Dir(abs))
}
write_synced_test.go 95 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

package syncfile

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

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

func TestCases(t *testing.T) {
	cases := []struct {
		name, text string
		before     *string
	}{
		{"new-file", "alpha\nbeta\n", nil},
		{"replace-longer", "short\n", ptr("a much longer old line\n")},
		{"many-lines", "one\ntwo\nthree\nfour\n", nil},
		{"empty-replace", "", ptr("old\n")},
		{"empty-new", "", nil},
		{"no-final-newline", "last line", nil},
		{"non-ascii", "naïve café\n日本語\n🙂\n", nil},
		{"crlf", "one\r\ntwo\r\n", nil},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			dir := t.TempDir()
			path := filepath.Join(dir, "out.txt")
			if c.before != nil {
				if err := os.WriteFile(path, []byte(*c.before), 0o644); err != nil {
					t.Fatal(err)
				}
			}
			if err := WriteSynced(path, c.text); err != nil {
				t.Fatal(err)
			}
			got, err := os.ReadFile(path)
			if err != nil || string(got) != c.text {
				t.Fatalf("got %q, %v; want %q", got, err, c.text)
			}
			if n := names(t, dir); len(n) != 1 || n[0] != "out.txt" {
				t.Fatalf("the directory holds %v", n)
			}
		})
	}
}

func ptr(s string) *string { return &s }

func TestSyncDirectory(t *testing.T) {
	if err := SyncDirectory(t.TempDir()); err != nil {
		t.Fatal(err)
	}
}

func TestMissingDirectory(t *testing.T) {
	dir := t.TempDir()
	err := WriteSynced(filepath.Join(dir, "missing", "out.txt"), "x\n")
	if !errors.Is(err, fs.ErrNotExist) {
		t.Fatalf("got %v, want not exist", err)
	}
	if n := names(t, dir); len(n) != 0 {
		t.Fatalf("the directory holds %v", n)
	}
}

func TestOntoDirectory(t *testing.T) {
	path := filepath.Join(t.TempDir(), "out.txt")
	if err := os.Mkdir(path, 0o755); err != nil {
		t.Fatal(err)
	}
	if err := WriteSynced(path, "x\n"); !errors.Is(err, syscall.EISDIR) {
		t.Fatalf("got %v, want EISDIR", err)
	}
	if fi, err := os.Stat(path); err != nil || !fi.IsDir() {
		t.Fatal("the directory is gone")
	}
}
write_synced.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

//! Writes a file and returns when its data is on the storage device.

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

/// Syncs the entries of `dir`, so that a new name in it is on disk. On Unix,
/// a directory opens for reading, and `sync_all` calls fsync on it.
pub fn sync_directory(dir: &Path) -> io::Result<()> {
    File::open(dir)?.sync_all()
}

/// Writes `text` to `path`, syncs the file, closes it, and syncs the
/// directory of `path`. Each step returns its error.
pub fn write_synced(path: &Path, text: &str) -> io::Result<()> {
    let mut f = File::create(path)?;
    // A File has no buffer: write_all gives all the bytes to the kernel.
    f.write_all(text.as_bytes())?;
    // sync_all also reports the errors that a drop of the File ignores.
    f.sync_all()?;
    drop(f);
    let abs = std::path::absolute(path)?;
    match abs.parent() {
        Some(dir) => sync_directory(dir),
        None => Ok(()),
    }
}
tests/write_synced_test.rs 81 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sync-a-file-to-disk/.

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

use algo_sync_a_file_to_disk::{sync_directory, write_synced};

struct Tree(PathBuf);

impl Tree {
    fn new(name: &str) -> Tree {
        let dir = std::env::temp_dir().join(format!("sync-file-{}-{name}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        Tree(dir)
    }

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

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

const CASES: &[(&str, &str, Option<&str>)] = &[
    ("new-file", "alpha\nbeta\n", None),
    ("replace-longer", "short\n", Some("a much longer old line\n")),
    ("many-lines", "one\ntwo\nthree\nfour\n", None),
    ("empty-replace", "", Some("old\n")),
    ("empty-new", "", None),
    ("no-final-newline", "last line", None),
    ("non-ascii", "naïve café\n日本語\n🙂\n", None),
    ("crlf", "one\r\ntwo\r\n", None),
];

#[test]
fn cases() {
    for (name, text, before) in CASES {
        let t = Tree::new(name);
        let path = t.0.join("out.txt");
        if let Some(b) = before {
            fs::write(&path, b).unwrap();
        }
        write_synced(&path, text).unwrap();
        assert_eq!(fs::read(&path).unwrap(), text.as_bytes(), "{name}");
        assert_eq!(t.names(), vec!["out.txt"], "{name}");
    }
}

#[test]
fn syncs_a_directory() {
    let t = Tree::new("dir");
    sync_directory(&t.0).unwrap();
}

#[test]
fn missing_directory() {
    let t = Tree::new("missing");
    let err = write_synced(&t.0.join("missing").join("out.txt"), "x\n").unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
    assert!(t.names().is_empty());
}

#[test]
fn onto_directory() {
    let t = Tree::new("onto");
    let path = t.0.join("out.txt");
    fs::create_dir(&path).unwrap();
    let err = write_synced(&path, "x\n").unwrap_err();
    assert_eq!(err.kind(), ErrorKind::IsADirectory);
    assert!(path.is_dir());
}
write_synced.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sync-a-file-to-disk/.

# write_synced PATH TEXT
# Writes TEXT to PATH with no newline at the end, and syncs the file and its
# directory. GNU sync syncs the files that it is
# given. The sync of macOS and BSD takes no file, so on those systems the
# function falls back to a sync of all file systems. It returns status 1 when
# the write or the sync fails.
write_synced() {
  local path=$1 text=$2 dir
  if [[ -d $path ]]; then
    printf 'write_synced: %s: Is a directory\n' "$path" >&2
    return 1
  fi
  printf '%s' "$text" > "$path" || return 1
  dir=$(dirname -- "$path")
  if sync --version >/dev/null 2>&1; then
    sync -- "$path" && sync -- "$dir"
  else
    sync
  fi
}
test_write_synced.bats 42 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sync-a-file-to-disk/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/write_synced.sh"
  dir=$BATS_TEST_TMPDIR/tree
  mkdir -p "$dir"
}

# check TEXT [BEFORE]: after write_synced, out.txt holds TEXT, and it is the
# only file. The x keeps the newlines at the end, which $( ) removes.
check() {
  local out
  if [ $# -gt 1 ]; then printf '%s' "$2" > "$dir/out.txt"; fi
  write_synced "$dir/out.txt" "$1" || return 1
  out=$(cat "$dir/out.txt" && printf x) || return 1
  [ "${out%x}" = "$1" ] || return 1
  [ "$(ls -A "$dir")" = out.txt ]
}

@test "new-file" { check $'alpha\nbeta\n'; }
@test "replace-longer" { check $'short\n' $'a much longer old line\n'; }
@test "many-lines" { check $'one\ntwo\nthree\nfour\n'; }
@test "empty-replace" { check '' $'old\n'; }
@test "empty-new" { check ''; }
@test "no-final-newline" { check 'last line'; }
@test "non-ascii" { check $'naïve café\n日本語\n🙂\n'; }
@test "crlf" { check $'one\r\ntwo\r\n'; }

@test "missing-directory" {
  run -1 write_synced "$dir/missing/out.txt" $'x\n'
  [ -z "$(ls -A "$dir")" ]
}

@test "onto-directory" {
  mkdir "$dir/out.txt"
  run -1 write_synced "$dir/out.txt" $'x\n'
  [ -d "$dir/out.txt" ]
}

References

  1. The Open Group Base Specifications Issue 8 (POSIX.1-2024), fsync, DESCRIPTION, APPLICATION USAGE, RATIONALE
  2. The Open Group Base Specifications Issue 8 (POSIX.1-2024), fdatasync, DESCRIPTION
  3. Linux manual page, fsync(2), DESCRIPTION, ERRORS
  4. Linux manual page, sync(2), DESCRIPTION
  5. Mac OS X manual page, fsync(2), DESCRIPTION
  6. PostgreSQL wiki, Fsync Errors, Current status, Open source kernels
  7. Pillai, Chidambaram, Alagappan, Al-Kiswany, Arpaci-Dusseau and Arpaci-Dusseau, All File Systems Are Not Created Equal: On the Complexity of Crafting Crash-Consistent Applications, OSDI 2014, Abstract
  8. The Python Standard Library, os, Miscellaneous operating system interfaces, os.fsync, os.fdatasync
  9. The Python Standard Library, io, Core tools for working with streams, IOBase.flush
  10. Node.js documentation, File system, fs.fsync, filehandle.sync()
  11. Java SE 25 API, FileChannel, force(boolean)
  12. .NET API reference, FileStream.Flush Method, Flush(Boolean)
  13. Go standard library, package os, func (*File) Sync
  14. The Rust Standard Library, std::fs::File, sync_all, sync_data
  15. cppreference, std::basic_ostream::flush, Description

About this page

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

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