tempnam

tempnam(string $directory, string $prefix): string|false

Temp-file naming: atomically creates a unique zero-byte file in the given directory (O_EXCL guards the TOCTOU race, mode 0600 on Unix) and returns the full path; the prefix is only a hint (first 63 chars, first 3 on Windows), with silent fallback to the system temp dir when the target is unwritable.

C C23

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

/* mkstemp: atomic create (O_EXCL, mode 0600); the template's trailing Xs get replaced */
int main(void) {
    const char *dir = getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp";
    char tmpl[256], tmpl2[256];
    snprintf(tmpl, sizeof tmpl, "%s/tmp_aXXXXXX", dir);
    snprintf(tmpl2, sizeof tmpl2, "%s/tmp_aXXXXXX", dir);
    int fd1 = mkstemp(tmpl);
    int fd2 = mkstemp(tmpl2);
    struct stat st;
    fstat(fd1, &st);
    printf("prefix ok: %d\n", strncmp(tmpl, dir, strlen(dir)) == 0);
    printf("created empty: %d\n", st.st_size == 0);
    printf("mode 600: %d\n", (st.st_mode & 0777) == 0600);
    printf("distinct: %d\n", strcmp(tmpl, tmpl2) != 0);
    close(fd1); close(fd2);
    unlink(tmpl); unlink(tmpl2);
    return 0;
}
Output
prefix ok: 1
created empty: 1
mode 600: 1
distinct: 1

C++ C++26

C++26
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <sys/stat.h>
#include <unistd.h>

// C++ has no temp-file helper (POSIX mkstemp or std::tmpfile in real work):
// the template's trailing Xs get replaced atomically (O_EXCL, mode 0600)
int main() {
    const char *dir = std::getenv("TMPDIR") ? std::getenv("TMPDIR") : "/tmp";
    char tmpl[256], tmpl2[256];
    std::snprintf(tmpl, sizeof tmpl, "%s/tmp_aXXXXXX", dir);
    std::snprintf(tmpl2, sizeof tmpl2, "%s/tmp_aXXXXXX", dir);
    int fd1 = mkstemp(tmpl);
    int fd2 = mkstemp(tmpl2);
    struct stat st{};
    ::fstat(fd1, &st);
    std::cout << std::boolalpha
              << "prefix ok: " << (std::strncmp(tmpl, dir, std::strlen(dir)) == 0) << "\n"
              << "created empty: " << (st.st_size == 0) << "\n"
              << "mode 600: " << ((st.st_mode & 0777) == 0600) << "\n"
              << "distinct: " << (std::strcmp(tmpl, tmpl2) != 0) << "\n";
    ::close(fd1); ::close(fd2);
    std::remove(tmpl); std::remove(tmpl2);
    return 0;
}
Output
prefix ok: true
created empty: true
mode 600: true
distinct: true

C# v11.0.100

v11.0.100
using System;
using System.IO;

// Path.GetTempFileName(): unique 0-byte .tmp file atomically (prefix fixed to "tmp")
var name1 = Path.GetTempFileName();
var name2 = Path.GetTempFileName();
Console.WriteLine("prefix ok: " + Path.GetFileName(name1).StartsWith("tmp"));
Console.WriteLine("created empty: " + (new FileInfo(name1).Length == 0));
Console.WriteLine("mode 600: " + (File.GetUnixFileMode(name1) == (UnixFileMode.UserRead | UnixFileMode.UserWrite)));
Console.WriteLine("distinct: " + (name1 != name2));
File.Delete(name1);
File.Delete(name2);
// GetRandomFileName(): name only, no creation - race-prone if you create it yourself later
Output
prefix ok: True
created empty: True
mode 600: True
distinct: True

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"os"
)

// os.CreateTemp: atomic create with a pattern; * is replaced by a unique suffix
func main() {
	f1, err := os.CreateTemp("", "tmp_a*")
	f2, _ := os.CreateTemp("", "tmp_a*")
	fmt.Println("created:", err == nil)
	fmt.Println("distinct:", f1.Name() != f2.Name())
	st, _ := f1.Stat()
	fmt.Println("created empty:", st.Size() == 0)
	fi, _ := f1.Stat()
	fmt.Println("mode 600:", fi.Mode().Perm() == 0600)
	f1.Close()
	f2.Close()
	os.Remove(f1.Name())
	os.Remove(f2.Name())
}
Output
created: true
distinct: true
created empty: true
mode 600: true

Java v27.0.1

v27.0.1
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;

public class Main {
    public static void main(String[] args) throws Exception {
        // createTempFile: atomic unique-name create; prefix/suffix are hints
        Path p1 = Files.createTempFile("tmp_a", ".tmp");
        Path p2 = Files.createTempFile("tmp_a", ".tmp");
        System.out.println("prefix ok: " + p1.getFileName().toString().startsWith("tmp_a"));
        System.out.println("created empty: " + (Files.size(p1) == 0));
        System.out.println("mode 600: " + PosixFilePermissions.toString(Files.getPosixFilePermissions(p1)).equals("rw-------"));
        System.out.println("distinct: " + !p1.equals(p2));
        Files.deleteIfExists(p1);
        Files.deleteIfExists(p2);
    }
}
Output
prefix ok: true
created empty: true
mode 600: true
distinct: true

JavaScript v26.13.1

v26.13.1
// Node has no atomic temp-FILE API: mkdtemp (directory) is the built-in primitive;
// files are hand-rolled with flag "wx" (O_EXCL) - the same atomic-create contract
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "tmp_a-"));
const inner = path.join(dir, "f.txt");
fs.writeFileSync(inner, "", { flag: "wx" }); // fails if the name exists: the race guard
console.log("prefix ok:", path.basename(dir).startsWith("tmp_a-"));
console.log("created empty:", fs.statSync(inner).size === 0);
const dir2 = fs.mkdtempSync(path.join(os.tmpdir(), "tmp_a-"));
console.log("distinct:", dir !== dir2);
fs.rmSync(dir, { recursive: true });
fs.rmSync(dir2, { recursive: true });
Output
prefix ok: true
created empty: true
distinct: true

PHP v8.6.0

v8.6.0
// tempnam: creates a UNIQUE file atomically (mode 0600), prefix is only a hint
$name1 = tempnam(sys_get_temp_dir(), "tmp_a");
$name2 = tempnam(sys_get_temp_dir(), "tmp_a");
echo "prefix ok: ", var_export(str_starts_with(basename($name1), "tmp_a"), true), "\n"; // first 63 chars; Windows: first 3
echo "created empty: ", var_export(file_exists($name1) && filesize($name1) === 0, true), "\n";
echo "mode 600: ", var_export((fileperms($name1) & 0777) === 0600, true), "\n"; // O_EXCL-safe private file
echo "distinct: ", var_export($name1 !== $name2, true), "\n"; // two calls never collide
unlink($name1);
unlink($name2);
Output
prefix ok: true
created empty: true
mode 600: true
distinct: true

Python v3.15.2

v3.15.2
import os
import stat as stat_mod
import tempfile

# mkstemp: creates the file atomically (O_EXCL, mode 0600) and returns (fd, path)
fd1, name1 = tempfile.mkstemp(prefix="tmp_a")
fd2, name2 = tempfile.mkstemp(prefix="tmp_a")
print("prefix ok:", os.path.basename(name1).startswith("tmp_a"))
print("created empty:", os.path.getsize(name1) == 0)
print("mode 600:", stat_mod.S_IMODE(os.stat(name1).st_mode) == 0o600)
print("distinct:", name1 != name2)
os.close(fd1)
os.close(fd2)
os.unlink(name1)
os.unlink(name2)
# mktemp (name only, no create) is DEPRECATED: the create-first APIs above are the fix
Output
prefix ok: True
created empty: True
mode 600: True
distinct: True

Rust v1.99.1

v1.99.1
use std::fs;
use std::fs::OpenOptions;
use std::io::Write;

// std has no temp-file helper (the tempfile crate in real projects):
// random name + create_new(true) = the atomic O_EXCL guarantee
fn create_temp(prefix: &str) -> std::path::PathBuf {
    let mut n = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .subsec_nanos();
    loop {
        let candidate = std::env::temp_dir().join(format!("{prefix}{n}"));
        match OpenOptions::new().write(true).create_new(true).open(&candidate) {
            Ok(_) => return candidate,
            Err(_) => n = n.wrapping_add(1), // name collision: retry with the next
        }
    }
}

fn main() {
    let name1 = create_temp("tmp_a");
    let name2 = create_temp("tmp_a");
    println!("prefix ok: {}", name1.file_name().unwrap().to_string_lossy().starts_with("tmp_a"));
    println!("created empty: {}", name1.metadata().map(|m| m.len()).unwrap_or(99) == 0);
    println!("distinct: {}", name1 != name2);
    fs::remove_file(&name1).unwrap();
    fs::remove_file(&name2).unwrap();
}
Output
prefix ok: true
created empty: true
distinct: true

TypeScript v26.13.1

v26.13.1
// Node has no atomic temp-FILE API: mkdtemp (directory) is the built-in primitive;
// files are hand-rolled with flag "wx" (O_EXCL) - the same atomic-create contract
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
const dir: string = fs.mkdtempSync(path.join(os.tmpdir(), "tmp_a-"));
const inner: string = path.join(dir, "f.txt");
fs.writeFileSync(inner, "", { flag: "wx" }); // fails if the name exists: the race guard
console.log("prefix ok:", path.basename(dir).startsWith("tmp_a-"));
console.log("created empty:", fs.statSync(inner).size === 0);
const dir2: string = fs.mkdtempSync(path.join(os.tmpdir(), "tmp_a-"));
console.log("distinct:", dir !== dir2);
fs.rmSync(dir, { recursive: true });
fs.rmSync(dir2, { recursive: true });
Output
prefix ok: true
created empty: true
distinct: true

Language differences

Chained with the existing sys_get_temp_dir entry (A22): resolve the temp directory first, then tempnam atomically creates a unique file inside it — deterministic assertions: the file exists with zero bytes, two calls never collide, and mode is 0600 (Unix).

The security semantics are this entry's soul: tempnam/mkstemp/CreateTempFile all use atomic O_EXCL creation — "name it + create it" in one step, eliminating the classic TOCTOU symlink race (the old mktemp-then-fopen pattern lets an attacker pre-occupy the name); Python's mktemp is deprecated for exactly this reason.

PHP surface: tempnam($dir, $prefix) returns false on failure; if the directory is unwritable it silently falls back to the system temp dir; the prefix uses only its first 63 characters (only 3 on Windows — the example's str_starts_with("tmp_a") assertion is compatible with both).

Language counterparts: Python tempfile.mkstemp (returns fd + path, mode 0600); C mkstemp (the six trailing Xs of the template get replaced; tmpnam is deprecated — don't); Java Files.createTempFile; C# Path.GetTempFileName (prefix fixed to "tmp", not customizable; GetRandomFileName names without creating); Go os.CreateTemp (the * in the pattern is replaced); Rust std has none (the tempfile crate) so the example hand-rolls create_new(true) = O_EXCL; JS/TS fs.mkdtemp is the directory-flavored builtin, with the file version hand-rolled via flag "wx" (O_EXCL).

The C++ standard library has no temp file helper (std::tmpfile is the C-inherited FILE* form and cannot give you the path); the example uses POSIX mkstemp (available under the validator's -D_GNU_SOURCE).