How to create temporary files

Create temporary files in Rust using std::env::temp_dir() and std::fs::File::create(), then manually delete them when finished.

Use std::env::temp_dir() to get the temporary directory path and std::fs::File::create() to generate a unique file within it. The OS automatically cleans up files in this directory on reboot, but you must manually delete them when your program finishes to avoid clutter.

use std::env;
use std::fs::File;
use std::io::Write;

fn main() {
    let temp_dir = env::temp_dir();
    let temp_file_path = temp_dir.join("my_temp_file.txt");
    
    let mut file = File::create(&temp_file_path).expect("Failed to create temp file");
    file.write_all(b"Temporary data").expect("Failed to write");
    
    // Clean up when done
    std::fs::remove_file(&temp_file_path).expect("Failed to delete temp file");
}