tempnam
tempnam(string $directory, string $prefix): string|false
临时文件命名:在指定目录原子创建唯一的 0 字节文件(O_EXCL 防 TOCTOU 竞态,Unix 下 mode 0600),返回完整路径;前缀只是提示(前 63 字符,Windows 前 3 字符),目录不可写时静默回退系统临时目录。
C C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
/* mkstemp:原子创建(O_EXCL,0600 权限);模板尾部的 X 被替换 */
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;
}
prefix ok: 1 created empty: 1 mode 600: 1 distinct: 1
C++ C++26
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <sys/stat.h>
#include <unistd.h>
// C++ 无临时文件助手(实战用 POSIX mkstemp 或 std::tmpfile):
// 模板尾部的 X 被原子替换(O_EXCL,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;
}
prefix ok: true created empty: true mode 600: true distinct: true
C# v11.0.100
using System;
using System.IO;
// Path.GetTempFileName():原子创建唯一的 0 字节 .tmp 文件(前缀固定 "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():只起名不创建——若之后自己再创建则有竞态风险
prefix ok: True created empty: True mode 600: True distinct: True
Go v1.27.4
package main
import (
"fmt"
"os"
)
// os.CreateTemp:按模式原子创建;* 被替换为唯一后缀
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())
}
created: true distinct: true created empty: true mode 600: true
Java 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:原子创建唯一命名文件;prefix/suffix 只是提示
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);
}
}
prefix ok: true created empty: true mode 600: true distinct: true
JavaScript v26.13.1
// Node 无原子临时文件 API:mkdtemp(目录)是内置原语;
// 文件用 "wx" 旗标(O_EXCL)手写——同一份原子创建契约
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" }); // 重名即失败:防竞态闸门
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 });
prefix ok: true created empty: true distinct: true
PHP v8.6.0
// tempnam:原子化创建唯一文件(0600 权限),前缀只是提示
$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"; // 只用前 63 字符;Windows 只用前 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 安全的私有文件
echo "distinct: ", var_export($name1 !== $name2, true), "\n"; // 两次调用绝不重名
unlink($name1);
unlink($name2);
prefix ok: true created empty: true mode 600: true distinct: true
Python v3.15.2
import os
import stat as stat_mod
import tempfile
# mkstemp:原子化创建文件(O_EXCL,0600 权限),返回 (fd, 路径)
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(只起名不创建)已弃用:上面这些"先创建"API 才是正解
prefix ok: True created empty: True mode 600: True distinct: True
Rust v1.99.1
use std::fs;
use std::fs::OpenOptions;
use std::io::Write;
// 标准库无临时文件助手(实战用 tempfile crate):
// 随机名 + create_new(true) = 原子 O_EXCL 保证
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), // 重名:换下一个名字重试
}
}
}
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();
}
prefix ok: true created empty: true distinct: true
TypeScript v26.13.1
// Node 无原子临时文件 API:mkdtemp(目录)是内置原语;
// 文件用 "wx" 旗标(O_EXCL)手写——同一份原子创建契约
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" }); // 重名即失败:防竞态闸门
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 });
prefix ok: true created empty: true distinct: true
语言差异说明
与既有 sys_get_temp_dir(A22)联动:先解析临时目录,tempnam 再在其中原子创建唯一文件——确定性断言:文件存在且 0 字节、两次调用名不同、mode 0600(Unix)。
安全语义是本条灵魂:tempnam/mkstemp/CreateTempFile 全走 O_EXCL 原子创建——「起名+创建」一步完成,杜绝经典 TOCTOU 符号链接竞态(先 mktemp 起名再 fopen 的老写法可被攻击者抢先占位);Python 的 mktemp 因此标记弃用。
PHP 面:tempnam($dir, $prefix) 失败返 false;目录不可写时静默回退系统临时目录;prefix 只用前 63 字符(Windows 只用前 3——示例断言 str_starts_with("tmp_a") 与之兼容)。
各语言对应:Python tempfile.mkstemp(返回 fd+路径,mode 0600)、C mkstemp(模板尾部 6 个 X 被替换;tmpnam 已弃用勿用)、Java Files.createTempFile、C# Path.GetTempFileName(前缀固定 tmp,无法自定义;GetRandomFileName 只起名不创建)、Go os.CreateTemp(pattern 中 * 被替换)、Rust std 无(tempfile crate)示例手写 create_new(true)=O_EXCL、JS/TS fs.mkdtemp 是目录版内置原语,文件版用 flag "wx"(O_EXCL)手写。
C++ 标准库无临时文件(std::tmpfile 是 C 继承的 FILE* 版,无法得路径名);示例用 POSIX mkstemp(校验器 -D_GNU_SOURCE 下可用)。