Guard Temporary Directories with RAII Cleanup
Create a unique temporary directory guarded by Drop cleanup, reject escaping write paths, and remove nested files automatically.
Code
use std::fs;
use std::io;
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(prefix: &str) -> io::Result<Self> {
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!("{prefix}-{}-{id}", std::process::id()));
fs::create_dir(&path)?;
Ok(Self { path })
}
fn path(&self) -> &Path {
&self.path
}
fn write(&self, name: &str, contents: &str) -> io::Result<PathBuf> {
let relative = Path::new(name);
let escapes = relative.components().any(|component| {
matches!(
component,
Component::ParentDir | Component::Prefix(_) | Component::RootDir
)
});
if relative.is_absolute() || escapes {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"path escapes the temporary directory",
));
}
let target = self.path.join(relative);
if let Some(parent) = target.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&target, contents)?;
Ok(target)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
fn main() -> io::Result<()> {
let dir = TempDir::new("devexamples")?;
let file = dir.write("nested/config.txt", "ok")?;
println!("wrote {}", file.display());
assert_eq!(fs::read_to_string(&file)?, "ok");
assert!(dir.write("../escape.txt", "no").is_err());
let path = dir.path().to_path_buf();
drop(dir);
assert!(!path.exists(), "temporary directory should be removed");
let second = TempDir::new("devexamples")?;
assert!(second.path().exists());
Ok(())
}
How it works
The TempDir struct is the whole surface: new creates a unique directory under std::env::temp_dir(), write validates the requested path, path lends the location out, and the Drop impl calls fs::remove_dir_all when the guard leaves scope.
Fallible operations return Result, and the ? operator short-circuits errors up to the caller.
Points of care
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Applying it
fn new(prefix: &str) -> io::Result<Self> combines the prefix, std::process::id() and a NEXT_ID.fetch_add counter into a collision-free directory name.
The run prints a single wrote line carrying the nested file’s path; the rejected "../escape.txt" write and the post-drop existence checks stay silent unless an assert! fails.
Running the file executes main, which drives new, write, path and drop in order.
Statements that matter
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"path escapes the temporary directory",
));
let file = dir.write("nested/config.txt", "ok")?;
fn new(prefix: &str) -> io::Result<Self> {
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!("{prefix}-{}-{id}", std::process::id()));
fs::create_dir(&path)?;
Ok(Self { path })
}
Interactive Tools for This Topic
FAQ
- Is there exception handling?
- As data, not exceptions: `Result` makes the caller handle both arms.
- What does Guard Temporary Directories with RAII Cleanup print when run?
- The script runs standalone; its 1 labeled outputs include `wrote`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.