# How do I create temporary files safely, and replace a file in one step?
Source: https://ruststudio.org/community/t/88/how-do-i-create-temporary-files-safely-and-replace-a-file-in-one-step
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, tempfile 3.27.0, Windows 11
Category: Help and questions | Kind: FAQ | Tags: security, files, tempfile | Views: 0

## Short answer
Use the tempfile crate: it creates files with unpredictable names and exclusive creation, and deletes them when dropped. To change an existing file, write a temporary file in the same folder and persist it over the target, so readers see the old or the new file but never a half-written one.

## Answer
## Answer
A temporary file with a **predictable** name in a shared folder (`/tmp/myapp.tmp`) is an old attack: another local user creates that name first, as a link to a file they want you to overwrite. The `tempfile` crate avoids it by creating the file with a random name and failing if the name already exists.

The same crate solves a second problem: crashes during writes. Write the new content to a temporary file in the **same directory** as the target (a rename across volumes is not atomic), then `persist` it over the target.

```toml title=Cargo.toml
[dependencies]
tempfile = "3"
```

```rust title=src/main.rs
use std::fs::OpenOptions;
use std::io::Write;
use tempfile::NamedTempFile;

fn main() -> std::io::Result<()> {
    let dir = tempfile::tempdir()?;
    let target = dir.path().join("settings.json");

    // Write the whole file under a random name, then move it into place in one step.
    let mut tmp = NamedTempFile::new_in(dir.path())?;
    tmp.write_all(b"{\"v\":1}")?;
    tmp.persist(&target).map_err(|e| e.error)?;
    println!("settings.json holds {} bytes", std::fs::metadata(&target)?.len());

    // create_new fails if the path already exists, so an existing file or link is never reused.
    let again = OpenOptions::new().write(true).create_new(true).open(&target);
    println!("second create_new: {:?}", again.map(|_| ()).map_err(|e| e.kind()));
    Ok(())
}
```

```text
settings.json holds 7 bytes
second create_new: Err(AlreadyExists)
```

`create_new(true)` is the standard-library way to say "create this file, and fail if anything is already there", which also refuses to follow a link that was put in place beforehand.

## How to do it
1. Use `NamedTempFile::new_in(dir)` for files that are renamed into place, and `tempfile::tempfile()` for scratch data with no name.
2. Write, flush, and only then `persist`.
3. Keep the directory private to the service account.
4. Use `create_new` whenever "this file must not exist yet" is part of the logic.

## Common mistakes
- Building a name from the process ID or the time.
- Using `fs::write` directly on a configuration file and losing it when the power fails halfway.
- Persisting into a different file system than the temporary file lives on.

## Related questions
### Is `persist` atomic on Windows?
The crate documents the behaviour of each platform; read its notes for the version you use before relying on atomic replacement.

### What is the difference between `tempfile()` and `NamedTempFile`?
`tempfile()` returns an unnamed file that disappears when closed. `NamedTempFile` has a path, which you need if you want to rename it into place.

## Sources
- `tempfile` documentation: https://docs.rs/tempfile/3.27.0/tempfile/
- Standard library, `OpenOptions::create_new`: https://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.create_new
