Programming Search⌘K

Taskcore

Create a temporary file

Also called temporary file, temp file, tmp file, mkstemp, mktemp, tmpfile, secure temporary file.

Make a new temporary file with a random name and the mode 0600 in one call, so that no other process can put a file or a link at the name first, then use it and remove it.

Task

Make a new, empty file with a random name in a directory, use it, and remove it. The task has two functions:

  • make_temp_file(dir, prefix) makes a new regular file in dir. Its name is prefix and then at least six random characters. Its mode is 0600: only the owner can read and write it. The function returns the path.
  • use_temp_file(dir, prefix, data) makes a file with make_temp_file, writes data to it, reads it back from the start, removes the file and returns the text. The name is random, so the cases test this function.

The important rule: make the file and check the name in one call. A temporary directory such as /tmp is shared by all users. When a program first picks a free name and then opens it, another process can put a file or a symbolic link at that name between the two steps. POSIX says that mkstemp acts "as if the O_EXCL flag for open () is set", and so "the function prevents any possible race condition between testing whether the file exists and opening it for use."

Report an error when dir does not exist, and when prefix has a slash, because then the file would go in another directory. SQL, regular expressions, HTML and CSS do not apply, because they do not make files. The solutions are for Linux and macOS.

Solutions

  • Python. tempfile.mkstemp(prefix=prefix, dir=dir) returns an open descriptor and the path. It "Creates a temporary file in the most secure manner possible. There are no race conditions in the file’s creation, assuming that the platform properly implements the os.O_EXCL flag for os.open() . The file is readable and writable only by the creating user ID." The caller closes the descriptor and removes the file. When the program does not need the name, tempfile.TemporaryFile() is simpler: "It will be destroyed as soon as it is closed".
  • JavaScript and TypeScript (Node.js). Node.js has mkdtemp for a directory, but no call that makes a temporary file. So the solution makes the name with crypto.randomBytes(6), which "Generates cryptographically strong pseudorandom data", and opens it with open(path, "wx", 0o600). The flag 'wx' is "Like 'w' but fails if the path exists". When the name is taken, it tries a new name.
  • Java. Files.createTempFile(dir, prefix, "", attrs). Without file attributes, the mode is not given: "the resulting file may have more restrictive access permissions than files created by the File.createTempFile(String,String,File) method." So the solution gives PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")). The suffix is "", because the documentation says that for a null suffix, .tmp is used.
  • C#. Path.GetTempFileName() "creates a temporary file with a .tmp file extension", and only in the folder that GetTempPath gives. It takes no directory and no prefix. So the solution makes the name with RandomNumberGenerator.GetString, which "Creates a string populated with characters chosen at random from choices", and opens it with FileMode.CreateNew and FileStreamOptions.UnixCreateMode, which "Gets or sets the Unix file mode used when a new file is created." When the name is taken, it tries a new name.
  • Go. os.CreateTemp(dir, prefix+"*"). It "creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting file." Also: "The file is created with mode 0o600 (before umask)." The * at the end is important. See the pitfalls.
  • Rust. The standard library has std::env::temp_dir, but no call that makes a temporary file. Its documentation says: "Consider using a crate that securely creates temporary files or directories." The solution uses only the standard library. It opens the name with OpenOptions::create_new, which fails when the file exists, "also no (dangling) symlink. In this way, if the call succeeds, the file returned is guaranteed to be new." It sets the mode with OpenOptionsExt::mode(0o600). The random part of the name is a hash from RandomState::new(), which "Constructs a new RandomState that is initialized with random keys". This hash is not a source of secure random numbers, but create_new makes the solution safe: the worst case is a name that is taken, and then the solution tries again.
  • C. POSIX mkstemp with the template dir/prefixXXXXXX. "The last six characters of template must be "XXXXXX" and these are replaced with a string that makes the filename unique." The template is changed in place, so it must be an array, not a string constant. The descriptor is open for reading and writing, so use_temp_file writes and reads through it, and does not open the name again.
  • C++. std::filesystem::temp_directory_path() gives "A directory suitable for temporary files", but the library has no call that makes a file. So the solution calls POSIX mkstemp, as in C, and returns a std::filesystem::path.
  • Bash. mktemp "$dir/${prefix}XXXXXX" makes the file and prints its name. The FreeBSD manual says: "If mktemp can successfully generate a unique file name, the file is created with mode 0600 (unless the -u flag is given) and the filename is printed to standard output." The script removes the file with rm -f on each path.

Edge cases

The cases are in cases/basic.jsonl, cases/edge.jsonl and cases/errors.jsonl. Each test runs in a new temporary directory that holds only the empty directory sub.

  • one-line, many-lines and in-subdirectory: the data comes back, and after the call, the directory holds only sub again.
  • empty-prefix: the name is only random characters.
  • empty-data: the file stays empty, and the result is the empty string.
  • non-ascii-data, prefix-with-spaces and non-ascii-prefix: café 日本, my temp and café-. A shell solution must quote the name.
  • Errors: the directory nodir gives not-found, and the prefix sub/tmp- gives invalid-prefix, and no file is made in sub.

The native tests also check make_temp_file: the name starts with the prefix and has at least six more characters, the file is a regular file and not a link, its permission bits are 0600, it is empty, and two calls give two different files.

A prefix that ends with X is not in the cases. POSIX says that mkstemp replaces "six or more 'X' characters at the end of the pathname", and the Node.js documentation says: "Some platforms, notably the BSDs, can return more than six random characters, and replace trailing X characters in prefix with random characters." So with mkstemp and mktemp, a prefix such as tmpX can lose its last X.

Pitfalls

  • A free name is not a file. tempfile.mktemp, tmpnam and the like give a name that is free now. POSIX says of tmpnam: "Between the time a pathname is created and the file is opened, it is possible for some other process to create a file with the same name." Here, another user puts a link at the name first, and the program writes through the link into a file of the user:

This code runs but gives a wrong answer on purpose.

import os
import tempfile

with open("victim.txt", "w") as f:
    f.write("important data\n")

name = tempfile.mktemp(dir=".")
# Another user makes a link at the free name before the program opens it.
os.symlink("victim.txt", name)

with open(name, "w") as f:
    f.write("temporary data\n")
with open("victim.txt") as f:
    print("victim.txt holds:", f.read(), end="")
Output
victim.txt holds: temporary data

Python says that mktemp "is not secure, because a different process may create a file with this name in the time between the call to mktemp() and the subsequent attempt to create the file by the first process. The solution is to combine the two steps and create the file immediately." With mkstemp, the file exists when the call returns, so no link can be put at its name:

import os
import stat
import tempfile

fd, path = tempfile.mkstemp(prefix="tmp-", dir=".")
print("mode:", oct(stat.S_IMODE(os.fstat(fd).st_mode)))
try:
    os.symlink("victim.txt", path)
except FileExistsError:
    print("the name is taken, so no link can go there")
os.close(fd)
os.remove(path)
Output
mode: 0o600
the name is taken, so no link can go there
  • A * in a Go prefix. In the pattern of os.CreateTemp, "If pattern includes a "", the random string replaces the last ""." So a prefix that has a * loses it, and the random part goes in the middle of the name. Add a * at the end of the prefix:

This code runs but gives a wrong answer on purpose.

package main

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

func main() {
	prefix := "data*backup-"
	f, err := os.CreateTemp(".", prefix)
	if err != nil {
		panic(err)
	}
	defer os.Remove(f.Name())
	defer f.Close()
	fmt.Println("with the pattern prefix:", strings.HasPrefix(filepath.Base(f.Name()), prefix))

	g, err := os.CreateTemp(".", prefix+"*")
	if err != nil {
		panic(err)
	}
	defer os.Remove(g.Name())
	defer g.Close()
	fmt.Println("with the pattern prefix+\"*\":", strings.HasPrefix(filepath.Base(g.Name()), prefix))
}
Output
with the pattern prefix: false
with the pattern prefix+"*": true
  • The file is not removed for you. Only some calls remove the file: Python TemporaryFile, and POSIX tmpfile, whose file "shall be automatically deleted when all references to the file are closed". With mkstemp, Python says: "the user of mkstemp() is responsible for closing the file descriptor (for example, using os.close() ) and deleting the temporary file". Go says: "It is the caller's responsibility to remove the file when it is no longer needed." Remove the file in a finally block, a defer or a destructor, so that an error does not leave it in the directory.

  • The mode of the file. A file made with a plain open gets the mode 0666, less the umask. Rust says: "If no mode is set, the default of 0o666 will be used. The operating system masks out bits with the system’s umask , to produce the final permissions." With a umask of 022, the mode is 0644, and all users can read the file. Ask for 0600 in the same call that makes the file, as all the solutions do. A chmod after the file is made leaves a short time when other users can open it.

  • Where the temporary directory is. Each language reads environment variables. Go says that TempDir "returns $TMPDIR if non-empty, else /tmp" on Unix, and "The directory is neither guaranteed to exist nor have accessible permissions." Python looks at TMPDIR, TEMP and TMP, and then at a list of directories. Rust says: "Note that the returned value may be a symbolic link, not a directory." So a program that makes many files, or large files, can take a directory as an argument, as the solutions do.

Code

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

temp_file.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-temporary-file/.

import os
import tempfile


def make_temp_file(dir: str | os.PathLike, prefix: str) -> str:
    """Makes a new, empty file in dir whose name starts with prefix, and returns its path.

    tempfile.mkstemp makes the file with os.O_EXCL and the mode 0600, and it
    returns an open descriptor, which this function closes. A prefix with a
    slash would put the file in another directory, so it is an error.
    """
    if "/" in prefix or os.sep in prefix:
        raise ValueError(f"invalid prefix: {prefix!r}")
    fd, path = tempfile.mkstemp(prefix=prefix, dir=dir)
    os.close(fd)
    return path


def use_temp_file(dir: str | os.PathLike, prefix: str, data: str) -> str:
    """Writes data to a new temporary file, reads it back, removes the file, and returns the text."""
    path = make_temp_file(dir, prefix)
    try:
        with open(path, "w+", encoding="utf-8", newline="") as f:
            f.write(data)
            f.seek(0)
            return f.read()
    finally:
        os.remove(path)
test_temp_file.py 66 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-temporary-file/.

import os
import stat
from pathlib import Path

import pytest

from temp_file import make_temp_file, use_temp_file

# name: (dir, prefix, data)
CASES = {
    "one-line": (".", "tmp-", "alpha\n"),
    "many-lines": (".", "report-", "alpha\nbeta\ngamma\n"),
    "in-subdirectory": ("sub", "tmp-", "alpha\n"),
    "empty-prefix": (".", "", "alpha\n"),
    "empty-data": (".", "tmp-", ""),
    "non-ascii-data": (".", "tmp-", "café 日本\n"),
    "prefix-with-spaces": (".", "my temp ", "alpha\n"),
    "non-ascii-prefix": (".", "café-", "alpha\n"),
}


@pytest.fixture
def root(tmp_path: Path) -> Path:
    (tmp_path / "sub").mkdir()
    return tmp_path


@pytest.mark.parametrize("name", CASES)
def test_cases(root: Path, name: str) -> None:
    rel, prefix, data = CASES[name]
    assert use_temp_file(root / rel, prefix, data) == data
    assert sorted(p.name for p in root.iterdir()) == ["sub"]
    assert list((root / "sub").iterdir()) == []


@pytest.mark.parametrize("prefix", ["tmp-", "", "my temp ", "café-"])
def test_make_temp_file(root: Path, prefix: str) -> None:
    path = Path(make_temp_file(root, prefix))
    assert path.parent == root
    assert path.name.startswith(prefix)
    assert len(path.name) >= len(prefix) + 6
    st = os.lstat(path)
    assert stat.S_ISREG(st.st_mode)
    assert stat.S_IMODE(st.st_mode) == 0o600
    assert st.st_size == 0


def test_two_calls_give_two_files(root: Path) -> None:
    a = make_temp_file(root, "tmp-")
    b = make_temp_file(root, "tmp-")
    assert a != b
    assert os.path.isfile(a) and os.path.isfile(b)


def test_missing_directory(root: Path) -> None:
    with pytest.raises(FileNotFoundError):
        use_temp_file(root / "nodir", "tmp-", "alpha\n")


def test_prefix_with_slash(root: Path) -> None:
    with pytest.raises(ValueError):
        use_temp_file(root, "sub/tmp-", "alpha\n")
    assert list((root / "sub").iterdir()) == []
temp_file.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

#include "temp_file.hpp"

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

#include <cerrno>
#include <fstream>
#include <iterator>
#include <vector>

namespace fs = std::filesystem;

namespace files {

namespace {

// open_temp gives the descriptor of mkstemp, or -1 with ec set.
int open_temp(const fs::path& dir, std::string_view prefix, fs::path& path, std::error_code& ec) {
    if (prefix.find('/') != std::string_view::npos) {
        ec = std::make_error_code(std::errc::invalid_argument);
        return -1;
    }
    std::string name = (dir / (std::string(prefix) + "XXXXXX")).string();
    std::vector<char> tmpl(name.begin(), name.end());
    tmpl.push_back('\0');
    int fd = ::mkstemp(tmpl.data());
    if (fd < 0) {
        ec.assign(errno, std::generic_category());
        return -1;
    }
    path = fs::path(tmpl.data());
    return fd;
}

}  // namespace

fs::path make_temp_file(const fs::path& dir, std::string_view prefix, std::error_code& ec) {
    ec.clear();
    fs::path path;
    int fd = open_temp(dir, prefix, path, ec);
    if (fd < 0) return {};
    if (::close(fd) != 0) {
        ec.assign(errno, std::generic_category());
        std::error_code ignored;
        fs::remove(path, ignored);
        return {};
    }
    return path;
}

std::string use_temp_file(const fs::path& dir, std::string_view prefix, std::string_view data,
                          std::error_code& ec) {
    fs::path path = make_temp_file(dir, prefix, ec);
    if (ec) return {};
    std::string text;
    {
        std::fstream f(path, std::ios::in | std::ios::out | std::ios::binary);
        f.write(data.data(), static_cast<std::streamsize>(data.size()));
        f.seekg(0);
        text.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
        if (!f.good() && !f.eof()) ec = std::make_error_code(std::errc::io_error);
    }
    std::error_code rm;
    fs::remove(path, rm);
    if (!ec && rm) ec = rm;
    return ec ? std::string() : text;
}

}  // namespace files
temp_file.hpp 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

#pragma once

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

namespace files {

// Makes a new, empty file in dir whose name is prefix followed by six random
// characters, with the mode 0600, and returns its path. std::filesystem has
// temp_directory_path, but no call that makes a file, so this uses POSIX
// mkstemp, which makes the file with O_CREAT | O_EXCL. On an error it sets ec
// and returns an empty path: std::errc::invalid_argument when prefix has a
// slash, and std::errc::no_such_file_or_directory when dir does not exist.
std::filesystem::path make_temp_file(const std::filesystem::path& dir, std::string_view prefix,
                                     std::error_code& ec);

// Writes data to a new temporary file, reads it back, removes the file, and
// returns the text. On an error it sets ec and returns an empty string.
std::string use_temp_file(const std::filesystem::path& dir, std::string_view prefix,
                          std::string_view data, std::error_code& ec);

}  // namespace files
test_temp_file.cpp 87 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

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

#include "temp_file.hpp"

namespace fs = std::filesystem;

namespace {

const fs::path dir = "temp_file_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 / "sub");
}

long count(const fs::path& d) {
    return std::distance(fs::directory_iterator(d), fs::directory_iterator());
}

}  // namespace

int main() {
    struct Case {
        const char *name, *rel, *prefix, *data;
    };
    const Case cases[] = {
        {"one-line", ".", "tmp-", "alpha\n"},
        {"many-lines", ".", "report-", "alpha\nbeta\ngamma\n"},
        {"in-subdirectory", "sub", "tmp-", "alpha\n"},
        {"empty-prefix", ".", "", "alpha\n"},
        {"empty-data", ".", "tmp-", ""},
        {"non-ascii-data", ".", "tmp-", "caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac\n"},
        {"prefix-with-spaces", ".", "my temp ", "alpha\n"},
        {"non-ascii-prefix", ".", "caf\xc3\xa9-", "alpha\n"},
    };
    std::error_code ec;
    for (const Case& c : cases) {
        fresh();
        std::string got = files::use_temp_file(dir / c.rel, c.prefix, c.data, ec);
        expect(!ec && got == c.data, c.name);
        expect(count(dir) == 1 && count(dir / "sub") == 0, c.name);
    }

    for (std::string prefix : {"tmp-", "", "my temp ", "caf\xc3\xa9-"}) {
        fresh();
        fs::path path = files::make_temp_file(dir, prefix, ec);
        std::string name = path.filename().string();
        expect(!ec && path.parent_path() == dir && name.starts_with(prefix) && name.size() >= prefix.size() + 6,
               "make: name " + prefix);
        auto st = fs::symlink_status(path);
        expect(fs::is_regular_file(st) && st.permissions() == (fs::perms::owner_read | fs::perms::owner_write) &&
                   fs::file_size(path) == 0,
               "make: mode and size " + prefix);
    }

    fresh();
    fs::path a = files::make_temp_file(dir, "tmp-", ec);
    fs::path b = files::make_temp_file(dir, "tmp-", ec);
    expect(!ec && a != b && count(dir) == 3, "two calls give two files");

    fresh();
    files::use_temp_file(dir / "nodir", "tmp-", "alpha\n", ec);
    expect(ec == std::errc::no_such_file_or_directory, "missing directory");
    files::use_temp_file(dir, "sub/tmp-", "alpha\n", ec);
    expect(ec == std::errc::invalid_argument, "prefix with a slash");
    expect(count(dir / "sub") == 0 && count(dir) == 1, "no file is left");

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

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;

public final class TempFile {
  private TempFile() {}

  /**
   * Makes a new, empty file in dir whose name starts with prefix, and returns its path.
   *
   * <p>Files.createTempFile makes the file only when no file has the name. Without file
   * attributes, the mode of the file is not given, so the call asks for rw------- itself. The
   * suffix is "", because a null suffix gives the name the end ".tmp".
   */
  public static Path makeTempFile(Path dir, String prefix) throws IOException {
    if (prefix.contains("/")) {
      throw new IllegalArgumentException("invalid prefix: " + prefix);
    }
    return Files.createTempFile(
        dir, prefix, "", PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
  }

  /** Writes data to a new temporary file, reads it back, removes the file, and returns the text. */
  public static String useTempFile(Path dir, String prefix, String data) throws IOException {
    Path path = makeTempFile(dir, prefix);
    try {
      Files.writeString(path, data, StandardCharsets.UTF_8);
      return Files.readString(path, StandardCharsets.UTF_8);
    } finally {
      Files.delete(path);
    }
  }
}
TempFileTest.java 90 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

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

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;

class TempFileTest {
  @TempDir Path dir;

  @BeforeEach
  void setUp() throws IOException {
    Files.createDirectory(dir.resolve("sub"));
  }

  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("one-line", ".", "tmp-", "alpha\n"),
        Arguments.of("many-lines", ".", "report-", "alpha\nbeta\ngamma\n"),
        Arguments.of("in-subdirectory", "sub", "tmp-", "alpha\n"),
        Arguments.of("empty-prefix", ".", "", "alpha\n"),
        Arguments.of("empty-data", ".", "tmp-", ""),
        Arguments.of("non-ascii-data", ".", "tmp-", "café 日本\n"),
        Arguments.of("prefix-with-spaces", ".", "my temp ", "alpha\n"),
        Arguments.of("non-ascii-prefix", ".", "café-", "alpha\n"));
  }

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

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void cases(String name, String rel, String prefix, String data) throws IOException {
    assertEquals(data, TempFile.useTempFile(dir.resolve(rel), prefix, data), name);
    assertEquals(List.of("sub"), names(dir));
    assertEquals(List.of(), names(dir.resolve("sub")));
  }

  @ParameterizedTest
  @ValueSource(strings = {"tmp-", "", "my temp ", "café-"})
  void makeTempFile(String prefix) throws IOException {
    Path path = TempFile.makeTempFile(dir, prefix);
    assertEquals(dir, path.getParent());
    String name = path.getFileName().toString();
    assertTrue(name.startsWith(prefix), name);
    assertTrue(name.length() >= prefix.length() + 6, name);
    assertTrue(Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS));
    assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(path)));
    assertEquals(0, Files.size(path));
  }

  @Test
  void twoCallsGiveTwoFiles() throws IOException {
    Path a = TempFile.makeTempFile(dir, "tmp-");
    Path b = TempFile.makeTempFile(dir, "tmp-");
    assertNotEquals(a, b);
    assertEquals(3, names(dir).size());
  }

  @Test
  void missingDirectory() {
    assertThrows(NoSuchFileException.class, () -> TempFile.useTempFile(dir.resolve("nodir"), "tmp-", "alpha\n"));
  }

  @Test
  void prefixWithSlash() throws IOException {
    assertThrows(IllegalArgumentException.class, () -> TempFile.useTempFile(dir, "sub/tmp-", "alpha\n"));
    assertEquals(List.of(), names(dir.resolve("sub")));
  }
}
temp_file.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

#define _POSIX_C_SOURCE 200809L

#include "temp_file.h"

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

// mkstemp replaces the six X characters at the end of the template, and it
// opens the file with O_CREAT | O_EXCL and the mode 0600 in one call.
static int open_temp(const char *dir, const char *prefix, char *path, size_t size) {
    if (strchr(prefix, '/') != NULL) {
        errno = EINVAL;
        return -1;
    }
    int n = snprintf(path, size, "%s/%sXXXXXX", dir, prefix);
    if (n < 0 || (size_t)n >= size) {
        errno = ERANGE;
        return -1;
    }
    return mkstemp(path);
}

int make_temp_file(const char *dir, const char *prefix, char *path, size_t size) {
    int fd = open_temp(dir, prefix, path, size);
    if (fd < 0) return -1;
    if (close(fd) != 0) {
        int e = errno;
        unlink(path);
        errno = e;
        return -1;
    }
    return 0;
}

char *use_temp_file(const char *dir, const char *prefix, const char *data) {
    char path[4096];
    int fd = open_temp(dir, prefix, path, sizeof path);
    if (fd < 0) return NULL;
    // The descriptor of mkstemp is open for reading and writing, so the
    // function writes and reads through it, and the name is not opened again.
    size_t len = strlen(data);
    char *text = malloc(len + 1);
    int e = 0;
    size_t done = 0;
    if (text == NULL) e = ENOMEM;
    while (e == 0 && done < len) {
        ssize_t w = write(fd, data + done, len - done);
        if (w < 0) e = errno;
        else done += (size_t)w;
    }
    if (e == 0 && lseek(fd, 0, SEEK_SET) < 0) e = errno;
    done = 0;
    while (e == 0 && done < len) {
        ssize_t r = read(fd, text + done, len - done);
        if (r < 0) e = errno;
        else if (r == 0) e = EIO;
        else done += (size_t)r;
    }
    if (close(fd) != 0 && e == 0) e = errno;
    if (unlink(path) != 0 && e == 0) e = errno;
    if (e != 0) {
        free(text);
        errno = e;
        return NULL;
    }
    text[len] = '\0';
    return text;
}
temp_file.h 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

#ifndef TEMP_FILE_H
#define TEMP_FILE_H

#include <stddef.h>

// make_temp_file makes a new, empty file in dir whose name is prefix followed
// by six random characters, with the mode 0600, and writes its path to path,
// which has room for size bytes. It returns 0, or -1 with errno: EINVAL when
// prefix has a slash, ERANGE when the path does not fit, or the errno of
// mkstemp, such as ENOENT when dir does not exist.
int make_temp_file(const char *dir, const char *prefix, char *path, size_t size);

// use_temp_file writes data to a new temporary file, reads it back, removes
// the file, and returns the text in a new string that the caller frees. It
// returns NULL with errno on an error.
char *use_temp_file(const char *dir, const char *prefix, const char *data);

#endif
test_temp_file.c 97 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

#define _POSIX_C_SOURCE 200809L

#include "temp_file.h"

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

static const char *dir = "temp_file_tree";
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 temp_file_tree") != 0 || mkdir(dir, 0755) != 0 || mkdir("temp_file_tree/sub", 0755) != 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;
}

int main(void) {
    static const struct {
        const char *name, *rel, *prefix, *data;
    } cases[] = {
        {"one-line", ".", "tmp-", "alpha\n"},
        {"many-lines", ".", "report-", "alpha\nbeta\ngamma\n"},
        {"in-subdirectory", "sub", "tmp-", "alpha\n"},
        {"empty-prefix", ".", "", "alpha\n"},
        {"empty-data", ".", "tmp-", ""},
        {"non-ascii-data", ".", "tmp-", "caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac\n"},
        {"prefix-with-spaces", ".", "my temp ", "alpha\n"},
        {"non-ascii-prefix", ".", "caf\xc3\xa9-", "alpha\n"},
    };
    char d[256], path[256];
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        fresh();
        snprintf(d, sizeof d, "%s/%s", dir, cases[i].rel);
        char *got = use_temp_file(d, cases[i].prefix, cases[i].data);
        expect(got != NULL && strcmp(got, cases[i].data) == 0, cases[i].name);
        free(got);
        expect(count(dir) == 1 && count("temp_file_tree/sub") == 0, cases[i].name);
    }

    static const char *prefixes[] = {"tmp-", "", "my temp ", "caf\xc3\xa9-"};
    for (size_t i = 0; i < sizeof prefixes / sizeof prefixes[0]; i++) {
        fresh();
        struct stat st;
        char want[256];
        snprintf(want, sizeof want, "%s/%s", dir, prefixes[i]);
        int ok = make_temp_file(dir, prefixes[i], path, sizeof path) == 0;
        expect(ok && strncmp(path, want, strlen(want)) == 0 && strlen(path) >= strlen(want) + 6, "make: name");
        expect(ok && lstat(path, &st) == 0 && S_ISREG(st.st_mode) && (st.st_mode & 07777) == 0600 && st.st_size == 0,
               "make: mode and size");
    }

    fresh();
    char a[256], b[256];
    expect(make_temp_file(dir, "tmp-", a, sizeof a) == 0 && make_temp_file(dir, "tmp-", b, sizeof b) == 0 &&
               strcmp(a, b) != 0 && count(dir) == 3,
           "two calls give two files");

    fresh();
    errno = 0;
    expect(use_temp_file("temp_file_tree/nodir", "tmp-", "alpha\n") == NULL && errno == ENOENT, "missing directory");
    errno = 0;
    expect(use_temp_file(dir, "sub/tmp-", "alpha\n") == NULL && errno == EINVAL, "prefix with a slash");
    errno = 0;
    char small[8];
    expect(make_temp_file(dir, "tmp-", small, sizeof small) == -1 && errno == ERANGE, "path too long");
    expect(count("temp_file_tree/sub") == 0 && count(dir) == 1, "no file is left");

    if (system("rm -rf temp_file_tree") != 0) failures++;
    if (failures != 0) return 1;
    printf("ok\n");
    return 0;
}
TempFile.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;

// Path.GetTempFileName makes a file only in the temporary folder of the user,
// with the end .tmp, and Directory.CreateTempSubdirectory makes a directory.
// So MakeTempFile makes the name from random characters, and opens it with
// FileMode.CreateNew, which fails when the path exists, and with the Unix mode
// 0600. It tries a new name when the name is taken.
[UnsupportedOSPlatform("windows")]
public static class TempFile
{
    private const string Chars = "abcdefghijklmnopqrstuvwxyz0123456789";

    private static FileStream Open(string dir, string prefix, out string path)
    {
        if (prefix.Contains('/'))
        {
            throw new ArgumentException($"invalid prefix: {prefix}", nameof(prefix));
        }
        var options = new FileStreamOptions
        {
            Mode = FileMode.CreateNew,
            Access = FileAccess.ReadWrite,
            UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite,
        };
        for (int attempt = 0; attempt < 100; attempt++)
        {
            path = Path.Combine(dir, prefix + RandomNumberGenerator.GetString(Chars, 10));
            try
            {
                return new FileStream(path, options);
            }
            catch (IOException) when (File.Exists(path) || Directory.Exists(path))
            {
                // Another file has the name: try a new name.
            }
        }
        throw new IOException("no free temporary name after 100 attempts");
    }

    public static string MakeTempFile(string dir, string prefix)
    {
        using FileStream f = Open(dir, prefix, out string path);
        return path;
    }

    public static string UseTempFile(string dir, string prefix, string data)
    {
        FileStream f = Open(dir, prefix, out string path);
        try
        {
            using (f)
            {
                byte[] bytes = new UTF8Encoding(false).GetBytes(data);
                f.Write(bytes);
                f.Position = 0;
                using var reader = new StreamReader(f, new UTF8Encoding(false));
                return reader.ReadToEnd();
            }
        }
        finally
        {
            File.Delete(path);
        }
    }
}
TempFileTests.cs 72 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

using System.Runtime.Versioning;
using Xunit;

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

    public TempFileTests() => Directory.CreateDirectory(Path.Combine(dir, "sub"));

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

    public static TheoryData<string, string, string, string> Cases => new()
    {
        { "one-line", ".", "tmp-", "alpha\n" },
        { "many-lines", ".", "report-", "alpha\nbeta\ngamma\n" },
        { "in-subdirectory", "sub", "tmp-", "alpha\n" },
        { "empty-prefix", ".", "", "alpha\n" },
        { "empty-data", ".", "tmp-", "" },
        { "non-ascii-data", ".", "tmp-", "café 日本\n" },
        { "prefix-with-spaces", ".", "my temp ", "alpha\n" },
        { "non-ascii-prefix", ".", "café-", "alpha\n" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void UsesTheFile(string name, string rel, string prefix, string data)
    {
        Assert.Equal(data, TempFile.UseTempFile(Path.Combine(dir, rel), prefix, data));
        Assert.Equal(new[] { "sub" }, Directory.GetFileSystemEntries(dir).Select(Path.GetFileName));
        Assert.Empty(Directory.GetFileSystemEntries(Path.Combine(dir, "sub")));
        Assert.True(name.Length > 0);
    }

    [Theory]
    [InlineData("tmp-")]
    [InlineData("")]
    [InlineData("my temp ")]
    [InlineData("café-")]
    public void MakesANewFile(string prefix)
    {
        string path = TempFile.MakeTempFile(dir, prefix);
        Assert.Equal(dir, Path.GetDirectoryName(path));
        string name = Path.GetFileName(path);
        Assert.StartsWith(prefix, name, StringComparison.Ordinal);
        Assert.True(name.Length >= prefix.Length + 6);
        var info = new FileInfo(path);
        Assert.Null(info.LinkTarget);
        Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(path));
        Assert.Equal(0, info.Length);
    }

    [Fact]
    public void TwoCallsGiveTwoFiles()
    {
        string a = TempFile.MakeTempFile(dir, "tmp-");
        string b = TempFile.MakeTempFile(dir, "tmp-");
        Assert.NotEqual(a, b);
        Assert.Equal(3, Directory.GetFileSystemEntries(dir).Length);
    }

    [Fact]
    public void Errors()
    {
        Assert.Throws<DirectoryNotFoundException>(() => TempFile.UseTempFile(Path.Combine(dir, "nodir"), "tmp-", "alpha\n"));
        Assert.Throws<ArgumentException>(() => TempFile.UseTempFile(dir, "sub/tmp-", "alpha\n"));
        Assert.Empty(Directory.GetFileSystemEntries(Path.Combine(dir, "sub")));
    }
}
tempFile.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

import { randomBytes } from "node:crypto";
import { open, rm } from "node:fs/promises";
import { join } from "node:path";

// Node.js has mkdtemp for a directory, but no call that makes a temporary
// file. So makeTempFile makes the name from random bytes, and opens it with
// the flag "wx", which fails when the path exists (O_CREAT | O_EXCL). It tries
// a new name when the name is taken, and it gives the mode 0o600.
export async function makeTempFile(dir, prefix) {
  if (prefix.includes("/")) {
    throw new RangeError(`invalid prefix: ${JSON.stringify(prefix)}`);
  }
  for (let attempt = 0; attempt < 100; attempt++) {
    const path = join(dir, prefix + randomBytes(6).toString("hex"));
    let handle;
    try {
      handle = await open(path, "wx", 0o600);
    } catch (err) {
      if (err.code === "EEXIST") continue;
      throw err;
    }
    await handle.close();
    return path;
  }
  throw new Error("no free temporary name after 100 attempts");
}

export async function useTempFile(dir, prefix, data) {
  const path = await makeTempFile(dir, prefix);
  try {
    const handle = await open(path, "r+");
    try {
      await handle.writeFile(data, "utf8");
      const buf = Buffer.alloc((await handle.stat()).size);
      await handle.read(buf, 0, buf.length, 0);
      return buf.toString("utf8");
    } finally {
      await handle.close();
    }
  } finally {
    await rm(path);
  }
}
tempFile.test.js 69 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

import assert from "node:assert/strict";
import { lstat, mkdir, mkdtemp, readdir, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { basename, dirname, join } from "node:path";
import { afterEach, beforeEach, test } from "node:test";

import { makeTempFile, useTempFile } from "./tempFile.js";

const cases = [
  ["one-line", ".", "tmp-", "alpha\n"],
  ["many-lines", ".", "report-", "alpha\nbeta\ngamma\n"],
  ["in-subdirectory", "sub", "tmp-", "alpha\n"],
  ["empty-prefix", ".", "", "alpha\n"],
  ["empty-data", ".", "tmp-", ""],
  ["non-ascii-data", ".", "tmp-", "café 日本\n"],
  ["prefix-with-spaces", ".", "my temp ", "alpha\n"],
  ["non-ascii-prefix", ".", "café-", "alpha\n"],
];

let dir;

beforeEach(async () => {
  dir = await mkdtemp(join(tmpdir(), "temp-file-"));
  await mkdir(join(dir, "sub"));
});

afterEach(async () => {
  await rm(dir, { recursive: true, force: true });
});

for (const [name, rel, prefix, data] of cases) {
  test(name, async () => {
    assert.equal(await useTempFile(join(dir, rel), prefix, data), data);
    assert.deepEqual(await readdir(dir), ["sub"]);
    assert.deepEqual(await readdir(join(dir, "sub")), []);
  });
}

for (const prefix of ["tmp-", "", "my temp ", "café-"]) {
  test(`make-temp-file ${JSON.stringify(prefix)}`, async () => {
    const path = await makeTempFile(dir, prefix);
    assert.equal(dirname(path), dir);
    assert.ok(basename(path).startsWith(prefix));
    assert.ok(basename(path).length >= prefix.length + 6);
    const st = await lstat(path);
    assert.ok(st.isFile());
    assert.equal(st.mode & 0o7777, 0o600);
    assert.equal(st.size, 0);
  });
}

test("two-calls-give-two-files", async () => {
  const a = await makeTempFile(dir, "tmp-");
  const b = await makeTempFile(dir, "tmp-");
  assert.notEqual(a, b);
  assert.equal((await readdir(dir)).length, 3);
});

test("missing-directory", async () => {
  await assert.rejects(useTempFile(join(dir, "nodir"), "tmp-", "alpha\n"), { code: "ENOENT" });
});

test("prefix-with-slash", async () => {
  await assert.rejects(useTempFile(dir, "sub/tmp-", "alpha\n"), RangeError);
  assert.deepEqual(await readdir(join(dir, "sub")), []);
});
tempFile.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

import { randomBytes } from "node:crypto";
import { type FileHandle, open, rm } from "node:fs/promises";
import { join } from "node:path";

// Node.js has mkdtemp for a directory, but no call that makes a temporary
// file. So makeTempFile makes the name from random bytes, and opens it with
// the flag "wx", which fails when the path exists (O_CREAT | O_EXCL). It tries
// a new name when the name is taken, and it gives the mode 0o600.
export async function makeTempFile(dir: string, prefix: string): Promise<string> {
  if (prefix.includes("/")) {
    throw new RangeError(`invalid prefix: ${JSON.stringify(prefix)}`);
  }
  for (let attempt = 0; attempt < 100; attempt++) {
    const path = join(dir, prefix + randomBytes(6).toString("hex"));
    let handle: FileHandle;
    try {
      handle = await open(path, "wx", 0o600);
    } catch (err) {
      if ((err as NodeJS.ErrnoException).code === "EEXIST") continue;
      throw err;
    }
    await handle.close();
    return path;
  }
  throw new Error("no free temporary name after 100 attempts");
}

export async function useTempFile(dir: string, prefix: string, data: string): Promise<string> {
  const path = await makeTempFile(dir, prefix);
  try {
    const handle = await open(path, "r+");
    try {
      await handle.writeFile(data, "utf8");
      const buf = Buffer.alloc((await handle.stat()).size);
      await handle.read(buf, 0, buf.length, 0);
      return buf.toString("utf8");
    } finally {
      await handle.close();
    }
  } finally {
    await rm(path);
  }
}
tempFile.test.ts 69 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

import assert from "node:assert/strict";
import { lstat, mkdir, mkdtemp, readdir, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { basename, dirname, join } from "node:path";
import { afterEach, beforeEach, test } from "node:test";

import { makeTempFile, useTempFile } from "./tempFile.ts";

const cases = [
  ["one-line", ".", "tmp-", "alpha\n"],
  ["many-lines", ".", "report-", "alpha\nbeta\ngamma\n"],
  ["in-subdirectory", "sub", "tmp-", "alpha\n"],
  ["empty-prefix", ".", "", "alpha\n"],
  ["empty-data", ".", "tmp-", ""],
  ["non-ascii-data", ".", "tmp-", "café 日本\n"],
  ["prefix-with-spaces", ".", "my temp ", "alpha\n"],
  ["non-ascii-prefix", ".", "café-", "alpha\n"],
];

let dir: string;

beforeEach(async () => {
  dir = await mkdtemp(join(tmpdir(), "temp-file-"));
  await mkdir(join(dir, "sub"));
});

afterEach(async () => {
  await rm(dir, { recursive: true, force: true });
});

for (const [name, rel, prefix, data] of cases) {
  test(name, async () => {
    assert.equal(await useTempFile(join(dir, rel), prefix, data), data);
    assert.deepEqual(await readdir(dir), ["sub"]);
    assert.deepEqual(await readdir(join(dir, "sub")), []);
  });
}

for (const prefix of ["tmp-", "", "my temp ", "café-"]) {
  test(`make-temp-file ${JSON.stringify(prefix)}`, async () => {
    const path = await makeTempFile(dir, prefix);
    assert.equal(dirname(path), dir);
    assert.ok(basename(path).startsWith(prefix));
    assert.ok(basename(path).length >= prefix.length + 6);
    const st = await lstat(path);
    assert.ok(st.isFile());
    assert.equal(st.mode & 0o7777, 0o600);
    assert.equal(st.size, 0);
  });
}

test("two-calls-give-two-files", async () => {
  const a = await makeTempFile(dir, "tmp-");
  const b = await makeTempFile(dir, "tmp-");
  assert.notEqual(a, b);
  assert.equal((await readdir(dir)).length, 3);
});

test("missing-directory", async () => {
  await assert.rejects(useTempFile(join(dir, "nodir"), "tmp-", "alpha\n"), { code: "ENOENT" });
});

test("prefix-with-slash", async () => {
  await assert.rejects(useTempFile(dir, "sub/tmp-", "alpha\n"), RangeError);
  assert.deepEqual(await readdir(join(dir, "sub")), []);
});
temp_file.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

// Package tempfile makes a temporary file with os.CreateTemp.
package tempfile

import (
	"errors"
	"os"
	"strings"
)

// ErrInvalidPrefix is the error for a prefix with a slash.
var ErrInvalidPrefix = errors.New("invalid prefix")

// MakeTempFile makes a new, empty file in dir whose name starts with prefix,
// and returns its path. os.CreateTemp makes the file with O_EXCL and the mode
// 0o600. In its pattern, the random string replaces the last "*", so a "*" is
// put after prefix: then a "*" in prefix stays as it is.
func MakeTempFile(dir, prefix string) (string, error) {
	if strings.ContainsRune(prefix, '/') {
		return "", ErrInvalidPrefix
	}
	f, err := os.CreateTemp(dir, prefix+"*")
	if err != nil {
		return "", err
	}
	name := f.Name()
	if err := f.Close(); err != nil {
		os.Remove(name)
		return "", err
	}
	return name, nil
}

// UseTempFile writes data to a new temporary file, reads it back, removes the
// file, and returns the text.
func UseTempFile(dir, prefix, data string) (string, error) {
	name, err := MakeTempFile(dir, prefix)
	if err != nil {
		return "", err
	}
	defer os.Remove(name)
	if err := os.WriteFile(name, []byte(data), 0o600); err != nil {
		return "", err
	}
	b, err := os.ReadFile(name)
	if err != nil {
		return "", err
	}
	return string(b), nil
}
temp_file_test.go 106 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

package tempfile

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

func newDir(t *testing.T) string {
	t.Helper()
	dir := t.TempDir()
	if err := os.Mkdir(filepath.Join(dir, "sub"), 0o755); err != nil {
		t.Fatal(err)
	}
	return dir
}

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) {
	cases := []struct{ name, rel, prefix, data string }{
		{"one-line", ".", "tmp-", "alpha\n"},
		{"many-lines", ".", "report-", "alpha\nbeta\ngamma\n"},
		{"in-subdirectory", "sub", "tmp-", "alpha\n"},
		{"empty-prefix", ".", "", "alpha\n"},
		{"empty-data", ".", "tmp-", ""},
		{"non-ascii-data", ".", "tmp-", "café 日本\n"},
		{"prefix-with-spaces", ".", "my temp ", "alpha\n"},
		{"non-ascii-prefix", ".", "café-", "alpha\n"},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			dir := newDir(t)
			got, err := UseTempFile(filepath.Join(dir, c.rel), c.prefix, c.data)
			if err != nil || got != c.data {
				t.Fatalf("got %q, %v; want %q", got, err, c.data)
			}
			if n := names(t, dir); len(n) != 1 || n[0] != "sub" {
				t.Fatalf("the directory holds %q", n)
			}
			if n := names(t, filepath.Join(dir, "sub")); len(n) != 0 {
				t.Fatalf("sub holds %q", n)
			}
		})
	}
}

func TestMakeTempFile(t *testing.T) {
	for _, prefix := range []string{"tmp-", "", "my temp ", "café-", "a*b-"} {
		dir := newDir(t)
		path, err := MakeTempFile(dir, prefix)
		if err != nil {
			t.Fatal(err)
		}
		name := filepath.Base(path)
		if filepath.Dir(path) != dir || !strings.HasPrefix(name, prefix) || len(name) < len(prefix)+6 {
			t.Fatalf("prefix %q: the path is %q", prefix, path)
		}
		fi, err := os.Lstat(path)
		if err != nil {
			t.Fatal(err)
		}
		if !fi.Mode().IsRegular() || fi.Mode().Perm() != 0o600 || fi.Size() != 0 {
			t.Fatalf("prefix %q: mode %v, size %d", prefix, fi.Mode(), fi.Size())
		}
	}
}

func TestTwoCallsGiveTwoFiles(t *testing.T) {
	dir := newDir(t)
	a, err1 := MakeTempFile(dir, "tmp-")
	b, err2 := MakeTempFile(dir, "tmp-")
	if err1 != nil || err2 != nil || a == b || len(names(t, dir)) != 3 {
		t.Fatalf("%q %v, %q %v", a, err1, b, err2)
	}
}

func TestErrors(t *testing.T) {
	dir := newDir(t)
	if _, err := UseTempFile(filepath.Join(dir, "nodir"), "tmp-", "alpha\n"); !errors.Is(err, fs.ErrNotExist) {
		t.Fatalf("missing directory: %v", err)
	}
	if _, err := UseTempFile(dir, "sub/tmp-", "alpha\n"); !errors.Is(err, ErrInvalidPrefix) {
		t.Fatalf("prefix with a slash: %v", err)
	}
	if n := names(t, filepath.Join(dir, "sub")); len(n) != 0 {
		t.Fatalf("sub holds %q", n)
	}
}
temp_file.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

//! The standard library of Rust gives the temporary directory, but no call
//! that makes a temporary file, and it has no random number generator. So
//! `make_temp_file` makes the name from the hash of a new `RandomState`,
//! whose keys are random, and opens it with `create_new`, which fails when
//! any file or link has the name (O_CREAT | O_EXCL). The name is hard to
//! guess, but the hash is not a secure random source: the safety comes from
//! `create_new`, which never opens a file that someone else made.

use std::fs::{self, OpenOptions};
use std::hash::{BuildHasher, RandomState};
use std::io::{self, ErrorKind, Read, Seek, SeekFrom, Write};
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

/// Makes a new, empty file in `dir` whose name starts with `prefix`, with the
/// mode 0o600, and returns its path.
pub fn make_temp_file(dir: &Path, prefix: &str) -> io::Result<PathBuf> {
    if prefix.contains('/') {
        return Err(io::Error::new(ErrorKind::InvalidInput, "invalid prefix"));
    }
    for attempt in 0..100u32 {
        let random = RandomState::new().hash_one((std::process::id(), attempt, SystemTime::now()));
        let path = dir.join(format!("{prefix}{random:016x}"));
        match OpenOptions::new().write(true).create_new(true).mode(0o600).open(&path) {
            Ok(_) => return Ok(path),
            Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
            Err(e) => return Err(e),
        }
    }
    Err(io::Error::new(ErrorKind::AlreadyExists, "no free temporary name after 100 attempts"))
}

/// Writes `data` to a new temporary file, reads it back, removes the file,
/// and returns the text.
pub fn use_temp_file(dir: &Path, prefix: &str, data: &str) -> io::Result<String> {
    let path = make_temp_file(dir, prefix)?;
    let result = (|| {
        let mut f = OpenOptions::new().read(true).write(true).open(&path)?;
        f.write_all(data.as_bytes())?;
        f.seek(SeekFrom::Start(0))?;
        let mut text = String::new();
        f.read_to_string(&mut text)?;
        Ok(text)
    })();
    fs::remove_file(&path)?;
    result
}
tests/temp_file_test.rs 91 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-temporary-file/.

use std::fs;
use std::io::ErrorKind;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};

use algo_create_a_temporary_file::{make_temp_file, use_temp_file};

struct Tree(PathBuf);

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

    fn path(&self, rel: &str) -> PathBuf {
        self.0.join(rel)
    }
}

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

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

#[test]
fn cases() {
    let cases = [
        ("one-line", ".", "tmp-", "alpha\n"),
        ("many-lines", ".", "report-", "alpha\nbeta\ngamma\n"),
        ("in-subdirectory", "sub", "tmp-", "alpha\n"),
        ("empty-prefix", ".", "", "alpha\n"),
        ("empty-data", ".", "tmp-", ""),
        ("non-ascii-data", ".", "tmp-", "café 日本\n"),
        ("prefix-with-spaces", ".", "my temp ", "alpha\n"),
        ("non-ascii-prefix", ".", "café-", "alpha\n"),
    ];
    for (name, rel, prefix, data) in cases {
        let tree = Tree::new(name);
        assert_eq!(use_temp_file(&tree.path(rel), prefix, data).unwrap(), data, "{name}");
        assert_eq!(names(&tree.0), ["sub"], "{name}");
        assert!(names(&tree.path("sub")).is_empty(), "{name}");
    }
}

#[test]
fn make_temp_file_name_and_mode() {
    for (i, prefix) in ["tmp-", "", "my temp ", "café-"].into_iter().enumerate() {
        let tree = Tree::new(&format!("make-{i}"));
        let path = make_temp_file(&tree.0, prefix).unwrap();
        assert_eq!(path.parent().unwrap(), tree.0);
        let name = path.file_name().unwrap().to_str().unwrap();
        assert!(name.starts_with(prefix) && name.len() >= prefix.len() + 6, "{name}");
        let meta = fs::symlink_metadata(&path).unwrap();
        assert!(meta.file_type().is_file());
        assert_eq!(meta.permissions().mode() & 0o7777, 0o600);
        assert_eq!(meta.len(), 0);
    }
}

#[test]
fn two_calls_give_two_files() {
    let tree = Tree::new("two");
    let a = make_temp_file(&tree.0, "tmp-").unwrap();
    let b = make_temp_file(&tree.0, "tmp-").unwrap();
    assert_ne!(a, b);
    assert_eq!(names(&tree.0).len(), 3);
}

#[test]
fn errors() {
    let tree = Tree::new("errors");
    let err = use_temp_file(&tree.path("nodir"), "tmp-", "alpha\n").unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
    let err = use_temp_file(&tree.0, "sub/tmp-", "alpha\n").unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidInput);
    assert!(names(&tree.path("sub")).is_empty());
}
temp_file.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-temporary-file/.

# make_temp_file DIR PREFIX
# Makes a new, empty file in DIR whose name is PREFIX followed by six random
# characters, and prints its path. mktemp makes the file with the mode 0600,
# and only when no file has the name. The function returns status 2 when
# PREFIX has a slash, and status 1 when mktemp fails, for example when DIR
# does not exist.
make_temp_file() {
  local dir=$1 prefix=$2
  if [[ $prefix == */* ]]; then
    printf 'make_temp_file: invalid prefix: %s\n' "$prefix" >&2
    return 2
  fi
  mktemp "$dir/${prefix}XXXXXX"
}

# use_temp_file DIR PREFIX DATA
# Writes DATA to a new temporary file, prints the file back, and removes it.
# A trap is not used, because a trap on RETURN would stay set in the shell
# that sources this file; the function removes the file on each path.
use_temp_file() {
  local dir=$1 prefix=$2 data=$3 path status=0
  path=$(make_temp_file "$dir" "$prefix") || return
  printf '%s' "$data" >"$path" && cat -- "$path" || status=1
  rm -f -- "$path"
  return "$status"
}
test_temp_file.bats 65 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-temporary-file/.

bats_require_minimum_version 1.5.0

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

# check DIR PREFIX DATA: use_temp_file prints DATA, and no file is left.
# The x keeps the newlines at the end, which $( ) removes.
check() {
  local out
  out=$(use_temp_file "$1" "$2" "$3" && printf x) || return 1
  [ "${out%x}" = "$3" ] || return 1
  [ "$(ls -A "$dir")" = sub ] || return 1
  [ -z "$(ls -A "$dir/sub")" ]
}

# mode PATH prints the permission bits, with GNU or BSD stat.
mode() {
  stat -c '%a' -- "$1" 2>/dev/null || stat -f '%Lp' -- "$1"
}

@test "one-line" { check "$dir" tmp- $'alpha\n'; }
@test "many-lines" { check "$dir" report- $'alpha\nbeta\ngamma\n'; }
@test "in-subdirectory" { check "$dir/sub" tmp- $'alpha\n'; }
@test "empty-prefix" { check "$dir" "" $'alpha\n'; }
@test "empty-data" { check "$dir" tmp- ""; }
@test "non-ascii-data" { check "$dir" tmp- $'café 日本\n'; }
@test "prefix-with-spaces" { check "$dir" "my temp " $'alpha\n'; }
@test "non-ascii-prefix" { check "$dir" café- $'alpha\n'; }

@test "make-temp-file" {
  local prefix path name
  for prefix in tmp- "" "my temp " café-; do
    path=$(make_temp_file "$dir" "$prefix")
    [ "${path%/*}" = "$dir" ]
    name=${path##*/}
    [[ $name == "$prefix"* ]]
    [ "${#name}" -ge $((${#prefix} + 6)) ]
    [ -f "$path" ] && [ ! -L "$path" ] && [ ! -s "$path" ]
    [ "$(mode "$path")" = 600 ]
  done
}

@test "two-calls-give-two-files" {
  local a b
  a=$(make_temp_file "$dir" tmp-)
  b=$(make_temp_file "$dir" tmp-)
  [ "$a" != "$b" ]
  [ "$(ls -A "$dir" | wc -l | tr -d ' ')" = 3 ]
}

@test "missing-directory" {
  run -1 use_temp_file "$dir/nodir" tmp- $'alpha\n'
}

@test "prefix-with-slash" {
  run -2 use_temp_file "$dir" sub/tmp- $'alpha\n'
  [ -z "$(ls -A "$dir/sub")" ]
}

References

  1. The Open Group Base Specifications Issue 8 (POSIX.1-2024), mkdtemp, mkostemp, mkstemp, DESCRIPTION
  2. The Open Group Base Specifications Issue 8 (POSIX.1-2024), tmpfile, DESCRIPTION
  3. The Open Group Base Specifications Issue 8 (POSIX.1-2024), tmpnam, APPLICATION USAGE
  4. Linux manual page, mkstemp(3), DESCRIPTION
  5. FreeBSD manual page, mktemp(1), DESCRIPTION
  6. The Python Standard Library, tempfile, Generate temporary files and directories, tempfile.mkstemp, tempfile.TemporaryFile, tempfile.mktemp, tempfile.tempdir
  7. Node.js documentation, File system, fsPromises.mkdtemp, File system flags
  8. Node.js documentation, OS, os.tmpdir()
  9. Node.js documentation, Crypto, crypto.randomBytes(size[, callback])
  10. Java SE 25 API, Files, createTempFile(Path, String, String, FileAttribute...)
  11. .NET API reference, Path.GetTempFileName Method, Remarks
  12. .NET API reference, FileStreamOptions.UnixCreateMode Property, Definition
  13. .NET API reference, RandomNumberGenerator.GetString Method, Definition
  14. Go standard library, package os, func CreateTemp, func MkdirTemp, func TempDir
  15. The Rust Standard Library, std::env::temp_dir, Description
  16. The Rust Standard Library, std::fs::OpenOptions, create_new
  17. The Rust Standard Library, std::os::unix::fs::OpenOptionsExt, mode
  18. The Rust Standard Library, std::hash::RandomState, Description, new
  19. cppreference, std::filesystem::temp_directory_path, Description, Return value

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