### Complete Example: Processing Unknown-Size Data with SpooledTempFile Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-spooledtempfile-struct.md A comprehensive example demonstrating how to write data of unknown size to a SpooledTempFile, check if it has rolled over to disk, and then read the data back after seeking to the beginning. ```Rust use tempfile::SpooledTempFile; use std::io::{Write, Read, Seek, SeekFrom}; let mut temp = SpooledTempFile::new(1024 * 1024); for chunk in &["small", "medium", "large", "very large chunk of data"] { write!(temp, "{} ", chunk)?; } println!("Rolled over: {}", temp.is_rolled()); temp.seek(SeekFrom::Start(0))?; let mut result = Vec::new(); temp.read_to_end(&mut result)?; println!("Total bytes: {}", result.len()); # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Example: Handling with Recovery Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-errors.md A comprehensive example demonstrating how to handle `PersistError` by extracting the error and recovering the file for a retry. ```APIDOC ### Example: Handling with Recovery ```rust use tempfile::NamedTempFile; use std::io::Write; let mut file = NamedTempFile::new()?; writeln!(file, "important data")?; match file.persist("./final.txt") { Ok(_) => println!("Success"), Err(err) => { println!("Persist failed: {{}}", err.error); let mut file = err.file; // File is still valid and contains data println!("Retrying with different path..."); match file.persist("./final2.txt") { Ok(_) => println!("Retry succeeded"), Err(e) => println!("Also failed: {{}}", e), } } } # Ok::<(), std::io::Error>(()) ``` ``` -------------------------------- ### Check and Log Temporary Directory Location Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-env-module.md This example demonstrates how to get the current temporary directory path using `env::temp_dir()` and print it to the console. This is useful for debugging or verifying where temporary files will be created. ```rust use tempfile::env; let temp = env::temp_dir(); println!("Temporary files will be created in: {:?}", temp); ``` -------------------------------- ### Create, Write, Seek, and Read Temporary File in Rust Source: https://github.com/stebalien/tempfile/blob/master/README.md This example demonstrates the basic usage of the tempfile library. It creates a temporary file, writes data to it, seeks back to the beginning, and then reads the data to verify its content. Ensure the tempfile crate is added to your Cargo.toml. ```rust use std::fs::File; use std::io::{Write, Read, Seek, SeekFrom}; fn main() { // Write let mut tmpfile: File = tempfile::tempfile().unwrap(); write!(tmpfile, "Hello World!").unwrap(); // Seek to start tmpfile.seek(SeekFrom::Start(0)).unwrap(); // Read let mut buf = String::new(); tmpfile.read_to_string(&mut buf).unwrap(); assert_eq!("Hello World!", buf); } ``` -------------------------------- ### Create Temporary Directory in Specific Location Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-tempdir_in-function.md Shows how to create a temporary directory in a specific storage location, such as '/var/cache', instead of the system's default temporary directory. Asserts that the created directory's path starts with the specified parent directory. ```rust use tempfile::tempdir_in; // Create temp directory in /var/cache instead of /tmp let cache_temp = tempdir_in("/var/cache")?; // Directory will be at /var/cache/.tmpXXXXXX assert!(cache_temp.path().starts_with("/var/cache")); # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### TempPath::try_from_path() Example Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-temppath-struct.md Creates a TempPath from an existing filesystem path. Relative paths are resolved against the current working directory, and empty paths will result in an error. This method returns a Result, allowing for proper error handling. ```rust use tempfile::TempPath; use std::path::PathBuf; let path = TempPath::try_from_path("./my-temp-file.txt")?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create a temporary directory with a prefix Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-tempdir-struct.md Use TempDir::with_prefix() to create a temporary directory with a specified name prefix. The full directory name will start with the provided prefix and be automatically cleaned up. ```rust use tempfile::TempDir; let dir = TempDir::with_prefix("build-")?; let name = dir.path().file_name().unwrap().to_str().unwrap(); assert!(name.starts_with("build-")); # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Pass TempPath to a Child Process Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-temppath-struct.md This example demonstrates creating a temporary file, writing data to it, closing the file handle to get a TempPath, and then passing this path to a child process using std::process::Command. The temporary file is explicitly closed and deleted afterward. ```rust use tempfile::NamedTempFile; use std::process::Command; use std::io::Write; // Create temp file let mut file = NamedTempFile::new()?; writeln!(file, "config data")?; // Get path only (close file handle) let temp_path = file.into_temp_path(); // Pass path to child process let output = Command::new("cat") .arg(temp_path.as_ref()) .output()?; // Explicitly delete and check for errors temp_path.close()?; println!("Output: {:?}", String::from_utf8(output.stdout)); # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Handle Already Set Temporary Directory Override Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-env-module.md This example shows how to handle the case where `override_temp_dir` has already been called, by checking the `Result` for `Ok` or `Err` to determine if the override was set or if it was already in use. ```rust use tempfile::env; use std::path::Path; match env::override_temp_dir(Path::new("/custom/tmp")) { Ok(()) => println!("Override set"), Err(prev) => println!("Already overridden to: {:?}", prev), } ``` -------------------------------- ### Use Current Temporary Directory in a Function Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-env-module.md This example shows how to obtain the current temporary directory using `env::temp_dir()` and then use it within a function to create a new temporary file. ```rust use tempfile::env; use std::fs; fn create_temp_file() -> std::io::Result { let temp_dir = env::temp_dir(); fs::File::create(temp_dir.join("my-temp.txt")) } let file = create_temp_file()?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Handling PersistError with Recovery Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-errors.md An example demonstrating how to handle a PersistError, log the underlying error, and attempt to re-persist the file. ```rust use tempfile::NamedTempFile; use std::io::Write; let mut file = NamedTempFile::new()?; writeln!(file, "important data")?; match file.persist("./final.txt") { Ok(_) => println!("Success"), Err(err) => { println!("Persist failed: {}", err.error); let mut file = err.file; // File is still valid and contains data println!("Retrying with different path..."); match file.persist("./final2.txt") { Ok(_) => println!("Retry succeeded"), Err(e) => println!("Also failed: {}", e), } } } # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Ensure Custom Temp Directory Exists Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-env-module.md This example demonstrates how to create a custom temporary directory and then override the default tempfile directory to use it. Ensure the directory exists before calling override_temp_dir. ```rust use tempfile::env; use std::path::Path; use std::fs; let custom_temp = "/tmp/myapp-temp"; fs::create_dir_all(custom_temp).ok(); env::override_temp_dir(Path::new(custom_temp))?; // All future tempfile operations use /tmp/myapp-temp # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create a SpooledTempFile with a Memory Threshold Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-spooledtempfile-struct.md Instantiate SpooledTempFile, specifying the maximum size in bytes to keep data in memory before spilling over to disk. This example sets the threshold to 5 MB. ```rust use tempfile::SpooledTempFile; use std::io::Write; struct Cache { data: SpooledTempFile, } impl Cache { fn new() -> Self { Cache { // Keep up to 5 MB in memory data: SpooledTempFile::new(5 * 1024 * 1024), } } fn add_entry(&mut self, key: &str, value: &str) -> std::io::Result<()> { writeln!(self.data, "{}: {}", key, value)?; if self.data.is_rolled() { println!("Cache exceeded 5 MB, using disk"); } Ok(()) } } let mut cache = Cache::new(); cache.add_entry("key1", "value1")?; cache.add_entry("key2", "very long value")?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create and Use a Temporary Directory Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-tempdir-struct.md Demonstrates creating a temporary directory, its subdirectories, and files. The directory and its contents are automatically deleted when the `TempDir` is dropped. Explicit cleanup or keeping the directory are also shown as commented-out options. ```rust use tempfile::TempDir; use std::fs::{self, File}; use std::io::Write; use std::path::Path; // Create a temporary directory with a specific prefix let dir = TempDir::with_prefix("myapp-")?; // Create subdirectories let subdir = dir.path().join("data"); fs::create_dir(&subdir)?; // Create files let file_path = subdir.join("config.json"); let mut file = File::create(file_path)?; writeln!(file, r#"{{"key": "value"}}"#)?; // Work with the directory... let entries = fs::read_dir(dir.path())?; // Option 1: Automatic cleanup on drop drop(file); drop(dir); // Directory and all contents deleted here // Option 2: Explicit cleanup // dir.close()?; // Option 3: Keep the directory // let path = dir.keep(); # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create Temporary Directory and File Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-tempdir_in-function.md Demonstrates creating a temporary directory within the current directory, creating a file inside it, writing data, and then explicitly closing the directory to ensure cleanup. ```rust use tempfile::tempdir_in; use std::fs::File; use std::io::Write; // Create temporary directory inside current directory let dir = tempdir_in("./")?; // Create a file inside let file_path = dir.path().join("data.txt"); let mut file = File::create(file_path)?; writeln!(file, "temporary data")?; drop(file); dir.close()?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create and Use a Temporary Directory Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-tempdir-function.md Demonstrates creating a temporary directory, writing a file into it, and explicitly closing the directory to check for errors. The directory and its contents are automatically removed when the `TempDir` object goes out of scope. ```rust use tempfile::tempdir; use std::fs::File; use std::io::Write; // Create a temporary directory let dir = tempdir()?; // Create a file inside it let file_path = dir.path().join("test.txt"); let mut file = File::create(file_path)?; writeln!(file, "test content")?; // Directory and all contents deleted when dir goes out of scope drop(file); dir.close()?; ``` -------------------------------- ### Create a new Builder instance Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-builder-struct.md Initializes a new Builder with default options for creating temporary files or directories. ```rust use tempfile::Builder; let builder = Builder::new(); ``` -------------------------------- ### Get Current Temporary Directory Path Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/QUICK_REFERENCE.md Retrieves and prints the current default temporary directory path used by the system. ```rust use tempfile::env; let temp_dir = env::temp_dir(); println!("Temps go to: {:?}", temp_dir); ``` -------------------------------- ### Get Temporary File Path Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-namedtempfile-struct.md Retrieve the immutable path to the temporary file. This is useful for passing the file location to other processes or libraries. ```rust use tempfile::NamedTempFile; let file = NamedTempFile::new()?; println!("File location: {:?}", file.path()); # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Accessing InMemory SpooledData Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-spooleddata-enum.md Demonstrates how to access and retrieve data from the InMemory variant of SpooledData. Use cursor.get_ref() to get an immutable reference to the data. ```rust use tempfile::SpooledTempFile; let file = SpooledTempFile::new(100); match file.into_inner() { tempfile::SpooledData::InMemory(cursor) => { let data = cursor.get_ref(); println!("In-memory data: {:?}", data); }, _ => {} } ``` -------------------------------- ### Get Temporary Directory Path Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-tempdir-struct.md Retrieves an immutable reference to the path of the temporary directory. Useful for interacting with the directory using standard file system operations. ```rust use tempfile::TempDir; use std::fs; let dir = TempDir::new()?; let entries = fs::read_dir(dir.path())?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Creating Resources Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/DOCUMENTATION_MANIFEST.md Functions for creating temporary files and directories with various options for naming and location. ```APIDOC ## Functions ### Creating Resources: - `tempfile()` — Create unnamed temporary file (most secure) - `tempfile_in()` — Create in specific directory - `tempdir()` — Create temporary directory - `tempdir_in()` — Create directory in specific location - `spooled_tempfile()` — Create in-memory file with disk spillover - `spooled_tempfile_in()` — Spooled file with explicit directory ``` -------------------------------- ### Pattern 3: Implementing Retry Logic for File Creation Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-errors.md Shows how to implement retry logic with a delay for creating temporary files, handling transient IO errors. ```rust use tempfile::NamedTempFile; use std::io::Error; fn create_with_retry(max_attempts: u32) -> std::io::Result { for attempt in 0..max_attempts { match NamedTempFile::new() { Ok(f) => return Ok(f), Err(e) if e.kind() == std::io::ErrorKind::Io && attempt < max_attempts - 1 => { std::thread::sleep(std::time::Duration::from_millis(100)); continue; }, Err(e) => return Err(e), } } unreachable!() } let file = create_with_retry(3)?; ``` -------------------------------- ### Creating Resources Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/INDEX.md Functions and methods for creating temporary files, directories, and spooled files with options for location and naming. ```APIDOC ## Creating Resources ### `tempfile()` **Description**: Creates an anonymous temporary file in the default temporary directory. This is the most secure option for temporary files. ### `tempfile_in(dir: &Path)` **Description**: Creates an anonymous temporary file within a specified directory. ### `tempdir()` **Description**: Creates a temporary directory in the default temporary directory. ### `tempdir_in(dir: &Path)` **Description**: Creates a temporary directory within a specified directory. ### `spooled_tempfile()` **Description**: Creates a spooled temporary file that starts in memory and spills over to disk if it exceeds a certain size. Uses the default temporary directory. ### `spooled_tempfile_in(dir: &Path)` **Description**: Creates a spooled temporary file within a specified directory. ### `NamedTempFile::new()` **Description**: Creates a named temporary file in the default temporary directory, providing an accessible path. ### `TempDir::new()` **Description**: Creates a temporary directory in the default temporary directory. ### `Builder::tempfile()` **Description**: Creates a named temporary file using a builder pattern, allowing for custom naming, permissions, and other configurations. ### `Builder::tempdir()` **Description**: Creates a temporary directory using a builder pattern, allowing for custom naming, permissions, and other configurations. ``` -------------------------------- ### Get Current Temporary Directory Path Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-env-module.md This function retrieves the path to the current temporary directory. It returns the overridden path if `override_temp_dir` was used, otherwise it delegates to `std::env::temp_dir()`. It does not validate directory existence. ```rust pub fn temp_dir() -> PathBuf ``` -------------------------------- ### Set Custom Permissions for Temporary Directory Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-tempdir-struct.md Shows how to create a temporary directory with specific file permissions using `Builder::permissions()`. This is useful for enforcing restrictive permissions on shared systems. ```rust use tempfile::Builder; use std::os::unix::fs::PermissionsExt; let perms = std::fs::Permissions::from_mode(0o700); let dir = Builder::new() .permissions(perms) .tempdir()?; ``` -------------------------------- ### Create a Simple Temporary File Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/INDEX.md Use `tempfile()` to create a temporary file that is automatically deleted when it goes out of scope. Requires `writeln!` macro. ```rust use tempfile::tempfile; let mut file = tempfile()?; writeln!(file, "data")?; // File deleted when dropped ``` -------------------------------- ### Create Temporary Directory with Custom Prefix Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/QUICK_REFERENCE.md Creates a temporary directory with a specified prefix for its name. ```rust use tempfile::TempDir; let dir = TempDir::with_prefix("build-")?; ``` -------------------------------- ### Configure Temporary File with Windows Permissions Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/configuration.md When creating temporary files on Windows, the `permissions` method is used, but only the read-only flag is respected. Other permission bits are ignored. ```rust use tempfile::Builder; use std::fs; let perms = fs::Permissions::new(); // perms.set_readonly(true); // Would cause creation to fail let file = Builder::new() .permissions(perms) .tempfile()?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create and Write to an Unnamed Temporary File Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-tempfile-function.md Demonstrates creating an unnamed temporary file, writing data to it, and relying on automatic cleanup when the file handle goes out of scope. No manual cleanup is required. ```rust use tempfile::tempfile; use std::io::Write; // Create an unnamed temporary file let mut file = tempfile()?; // Write some data writeln!(file, "This is temporary data")?; // File is automatically deleted when `file` goes out of scope // No manual cleanup needed # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create and Use a Temporary Directory Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/QUICK_REFERENCE.md Creates a temporary directory, a file within it, and explicitly closes the directory, checking for errors. ```rust use tempfile::tempdir; use std::fs::File; let dir = tempdir()?; let file = File::create(dir.path().join("test.txt"))?; dir.close()?; // Explicit close checks errors ``` -------------------------------- ### Create a Temporary Directory Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/README.md Use `tempdir()` to create a temporary directory. The directory and its contents are automatically deleted when the `TempDir` guard is dropped. ```rust use tempfile::tempdir; let dir = tempdir()?; let file_path = dir.path().join("file.txt"); ``` -------------------------------- ### Configuration - Builder Options Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/DOCUMENTATION_MANIFEST.md Table detailing the available options for the Builder, including their type and default values. ```APIDOC #### Builder Options | Option | Type | Default | |--------|------|---------| | prefix | &OsStr | ".tmp" | | suffix | &OsStr | "" | | rand_bytes | usize | 6 | | append | bool | false | | permissions | Option | platform-default | | disable_cleanup | bool | false | ``` -------------------------------- ### Configure Temporary File with All Options Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/configuration.md Use `Builder` to configure a temporary file with custom prefix, suffix, random bytes, append mode, strict permissions, and a specific directory. Ensure the path contains the specified prefix. ```rust use tempfile::Builder; use std::fs::Permissions; use std::os::unix::fs::PermissionsExt; // Configure a temporary file with all options let file = Builder::new() .prefix("app-") // prefix .suffix(".tmp") // suffix .rand_bytes(10) // more randomness .append(false) // write/truncate mode .permissions( Permissions::from_mode(0o600) ) .tempfile_in("/var/cache")?; assert!(file.path().to_string_lossy().contains("app-")); # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Configure Temporary File Creation Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/INDEX.md Use `Builder` to configure options like prefix, suffix, and random bytes for temporary file creation. The `tempfile()` method on the builder creates the file. ```rust use tempfile::Builder; let file = Builder::new() .prefix("app-") .suffix(".log") .rand_bytes(8) .tempfile()?; ``` -------------------------------- ### Builder::new() Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-builder-struct.md Creates a new Builder instance with default configuration options. ```APIDOC ## Builder::new() ### Description Creates a new `Builder` with default options. ### Returns `Builder` instance ### Example ```rust use tempfile::Builder; let builder = Builder::new(); ``` ``` -------------------------------- ### Basic Error Handling for Tempfile Creation Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/QUICK_REFERENCE.md Demonstrates the basic pattern for handling errors when creating a new named temporary file using `NamedTempFile::new()`. It uses a `match` statement to differentiate between successful creation and error scenarios. ```rust use tempfile::NamedTempFile; match NamedTempFile::new() { Ok(f) => { /* use f */ }, Err(e) => println!("Error: {}", e), } ``` -------------------------------- ### make() Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-builder-struct.md Creates a temporary file-like object using a custom closure. The closure is responsible for creating the actual file-like object at a given path. Retries are handled automatically if the path is already in use. ```APIDOC ## make() ### Description Create a temporary file-like object using a custom closure. ### Parameters #### Path Parameters - `f` (F) - Required - Closure that takes a path and returns `io::Result` ### Purpose Enables creating file-like objects (Unix sockets, pipes) with temp path management. ### Security The closure must ensure atomicity - check AND create must be a single operation. ### Retries If the closure returns `AlreadyExists` or `AddrInUse`, a new path is tried automatically. ### Request Example ```rust use tempfile::Builder; use std::os::unix::net::UnixListener; let tempsock = Builder::new().make(|path| { UnixListener::bind(path) })?; # Ok::<(), std::io::Error>(()) ``` ``` -------------------------------- ### Custom File Creation with Builder::make() Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/configuration.md Use `Builder::make()` for custom file-like objects such as sockets or pipes. This allows specifying a custom creation function that takes a path. ```rust use tempfile::Builder; use std::os::unix::net::UnixListener; let temp_socket = Builder::new() .prefix("sock-") .make(|path| UnixListener::bind(path))?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create a NamedTempFile with a prefix Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-namedtempfile-struct.md Creates a new named temporary file with a specified filename prefix. Returns an io::Error if file creation fails. ```rust use tempfile::NamedTempFile; let file = NamedTempFile::with_prefix("cache-")?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create Temporary File in Application Cache Directory Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-tempfile_in-function.md Shows how to create a temporary file within a specific application cache directory using `tempfile_in`. This bypasses the system's default temporary directory. The temporary file is managed by the OS for cleanup. ```rust use tempfile::tempfile_in; use std::path::Path; let cache_dir = "/var/cache/myapp"; let temp = tempfile_in(cache_dir)?; // This temporary file will be in the cache directory // instead of system temp # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Set Unix/Linux File Permissions with Builder Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/configuration.md Configure specific Unix-like file permissions (e.g., owner read/write) for temporary files using the `permissions` method with `PermissionsExt`. Note that actual permissions are affected by umask. ```rust use tempfile::Builder; use std::os::unix::fs::PermissionsExt; let perms = Permissions::from_mode(0o600); // Owner read/write only let file = Builder::new() .permissions(perms) .tempfile()?; // Actual permissions = 0o600 & !umask // With standard umask 0o022, result is 0o600 # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Build Directory Structure in Temporary Directory Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-tempdir-function.md Shows how to create a subdirectory within a temporary directory. The entire structure is automatically cleaned up when the root `TempDir` object is dropped. ```rust use tempfile::tempdir; use std::fs; let root = tempdir()?; let subdir = root.path().join("subdir"); fs::create_dir(&subdir)?; // Work with nested directories... // All cleaned up automatically ``` -------------------------------- ### Configure Temporary File with WASI Permissions Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/configuration.md On WASI platforms, the `permissions` method has no effect as the platform does not have a permission model. The `tempfile()` call will ignore any provided permissions. ```rust use tempfile::Builder; use std::fs::Permissions; let perms = Permissions::new(); let file = Builder::new() .permissions(perms) .tempfile()?; // Permissions ignored on WASI # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Configure Tempfile Creation with Builder Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/QUICK_REFERENCE.md Uses the `Builder` pattern to configure various options for creating a temporary file, including prefix, suffix, randomness, append mode, permissions, and the directory. This provides fine-grained control over temporary file creation. ```rust use tempfile::Builder; use std::fs::Permissions; use std::os::unix::fs::PermissionsExt; let file = Builder::new() .prefix("myapp-") // Name prefix .suffix(".tmp") // Name suffix .rand_bytes(8) // More randomness .append(true) // Append mode (files only) .permissions( Permissions::from_mode(0o600) ) // File permissions (Unix) .disable_cleanup(false) // Manual cleanup .tempfile_in("/tmp")?; ``` -------------------------------- ### Create a spooled temp file with a size limit Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-spooled_tempfile-function.md Demonstrates creating a `SpooledTempFile` with a specific memory limit and observing the rollover behavior when data exceeds this limit. The `is_rolled()` method checks if the file has transitioned to disk storage. ```rust use tempfile::spooled_tempfile; use std::io::Write; // Create a spooled file with 15-byte limit let mut file = spooled_tempfile(15); // This stays in memory writeln!(file, "short")?; assert!(!file.is_rolled()); // This causes rollover to disk writeln!(file, "much longer line")?; assert!(file.is_rolled()); // Continue writing (now to disk) writeln!(file, "more data")?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Correctly Passing TempDir to Command Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-tempdir-struct.md Demonstrates the correct way to pass a temporary directory to an external command by keeping the `TempDir` object alive. Avoids dropping the directory before the command finishes. ```rust use tempfile::tempdir; use std::process::Command; let dir = tempdir()?; // CORRECT: dir is kept alive Command::new("touch").arg("file").current_dir(&dir).status()?; // WRONG: dir dropped before command runs // Command::new("touch").arg("file").current_dir(dir.path().to_owned()).status()?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create Config File with Builder Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/QUICK_REFERENCE.md Use `tempfile::Builder` to create temporary files with custom options like suffixes. Persist the file to a specific location using `persist()`. Ensure the file handle is managed appropriately. ```rust use tempfile::Builder; use std::io::Write; let mut f = Builder::new() .suffix(".conf") .tempfile()?; writeln!(f, "[config]\nkey = value")?; f.persist("/etc/myapp.conf")?; ``` -------------------------------- ### Create a Temporary File with Path Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/README.md Use `NamedTempFile::new()` to create a temporary file that has an accessible path. You can then reference the file by its path or persist it to a permanent location. ```rust use tempfile::NamedTempFile; let file = NamedTempFile::new()?; let path = file.path(); // Can reference by path file.persist("./final.txt")?; ``` -------------------------------- ### Create Simple Temporary File Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/_START_HERE.txt Creates a simple temporary file that is automatically deleted when it goes out of scope. Requires `tempfile::tempfile` and `std::io::Write`. ```rust use tempfile::tempfile; use std::io::Write; let mut f = tempfile()?; write!(f, "data")?; ``` -------------------------------- ### Configure Temporary File Creation Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/README.md Use `Builder` to configure custom behavior when creating temporary files, such as setting a prefix and suffix for the filename. ```rust use tempfile::Builder; let file = Builder::new() .prefix("myapp-") .suffix(".log") .tempfile()?; ``` -------------------------------- ### Multiple File Handles to an Unnamed Temporary File Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-tempfile-function.md Shows how to create an unnamed temporary file, write to it, and then create multiple handles to the same file. This allows for concurrent reading or writing operations using different handles to the same underlying temporary file. ```rust use tempfile::tempfile; use std::fs::File; use std::io::{Write, Read}; // Create an unnamed temp file let mut file = tempfile()?; // Write some data writeln!(file, "Hello from producer")?; // Rewind to beginning file.seek(std::io::SeekFrom::Start(0))?; // Create another handle to the same file let file_handle = file.try_clone()?; // Both handles can now be used for reading/writing # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create Configured Temporary File Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/_START_HERE.txt Creates a temporary file with custom prefix and suffix using `tempfile::Builder`. The file is automatically deleted when it goes out of scope. ```rust use tempfile::Builder; let f = Builder::new() .prefix("app-") .suffix(".log") .tempfile()?; ``` -------------------------------- ### Create a new temporary directory Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-tempdir-struct.md Use TempDir::new() to create a temporary directory in the default system temp location. The directory is automatically deleted when the TempDir value is dropped. Errors are returned if directory creation fails. ```rust use tempfile::TempDir; let dir = TempDir::new()?; println!("Temp directory at: {:?}", dir.path()); # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create a Temporary Directory and File Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/INDEX.md Use `tempdir()` to create a temporary directory. Files can be created within this directory using standard `std::fs::File` operations. The directory and its contents are cleaned up when `dir.close()` is called or when the `TempDir` goes out of scope. ```rust use tempfile::tempdir; use std::fs::File; use std::io::Write; let dir = tempdir()?; let file_path = dir.path().join("data.txt"); let mut file = File::create(&file_path)?; writeln!(file, "content")?; dir.close()?; ``` -------------------------------- ### Builder::prefix() Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-builder-struct.md Sets the filename prefix for the temporary file or directory. ```APIDOC ## Builder::prefix() ### Description Set the filename prefix. ### Method `&mut self` ### Parameters #### Path Parameters - **prefix** (`&'a S`) - Required - Prefix string (path separators allowed but not recommended) ### Default `.tmp` ### Example ```rust use tempfile::Builder; let file = Builder::new() .prefix("myapp-") .tempfile()?; # Ok::<(), std::io::Error>(()) ``` ``` -------------------------------- ### Create a Temporary File with a Path Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/INDEX.md Use `NamedTempFile::new()` to create a temporary file that has a persistent path on the filesystem. The file is deleted when the `NamedTempFile` is dropped. ```rust use tempfile::NamedTempFile; let mut file = NamedTempFile::new()?; println!("Path: {:?}", file.path()); ``` -------------------------------- ### Import Paths for Tempfile Types and Functions Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/types.md Import all necessary types and functions from the tempfile crate root. This includes Builder, NamedTempFile, TempDir, TempPath, SpooledTempFile, SpooledData, and error types, as well as utility functions like tempfile, tempdir, and spooled_tempfile. ```rust use tempfile::Builder; use tempfile::NamedTempFile; use tempfile::TempDir; use tempfile::TempPath; use tempfile::SpooledTempFile; use tempfile::SpooledData; use tempfile::PathPersistError; use tempfile::PersistError; use tempfile::env; // Functions use tempfile::tempfile; use tempfile::tempfile_in; use tempfile::tempdir; use tempfile::tempdir_in; use tempfile::spooled_tempfile; use tempfile::spooled_tempfile_in; ``` -------------------------------- ### Temporary Working Directory Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/QUICK_REFERENCE.md Create a temporary directory using `tempdir()` for isolated work. Remember to change back to the original directory and explicitly call `dir.close()` to ensure cleanup and error checking. ```rust use tempfile::tempdir; use std::fs; let dir = tempdir()?; let old = std::env::current_dir()?; std::env::set_current_dir(dir.path())?; // Do work... std::env::set_current_dir(old)?; dir.close()?; ``` -------------------------------- ### Create Temporary Directory Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/_START_HERE.txt Creates a temporary directory that is automatically deleted when it goes out of scope. Use `tempfile::tempdir` for this. ```rust use tempfile::tempdir; let dir = tempdir()?; let file_path = dir.path().join("file.txt"); ``` -------------------------------- ### Create a Secure Temporary File Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/README.md Use `tempfile()` to create an unnamed temporary file. The file is automatically deleted by the OS when all handles are closed. This is the most secure method. ```rust use tempfile::tempfile; let mut file = tempfile()?; // File automatically deleted by OS when all handles close ``` -------------------------------- ### Rust: Create Temporary File-like Object with Custom Closure Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-builder-struct.md Use the `make()` method to create a temporary file-like object using a custom closure. This is useful for creating objects like Unix domain sockets or pipes with temporary path management. The closure must ensure atomicity, and the builder automatically retries on `AlreadyExists` or `AddrInUse` errors. ```rust use tempfile::Builder; use std::os::unix::net::UnixListener; let tempsock = Builder::new().make(|path| { UnixListener::bind(path) })?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Create a Temporary File with a Persistent Path Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/INDEX.md Use `NamedTempFile::new()` to create a temporary file that has a path on the filesystem. The file is automatically cleaned up unless persisted. `file.persist()` moves the file to a new location. ```rust use tempfile::NamedTempFile; let file = NamedTempFile::new()?; println!("Path: {:?}", file.path()); file.persist("./final.txt")?; ``` -------------------------------- ### Application Setting Custom Temp Directory Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-env-module.md Applications can set a custom temporary directory at startup using `override_temp_dir`. Subsequent calls to default tempfile functions will use this directory. The directory is not validated until it is used. ```rust use tempfile::{tempfile_in, tempdir_in, env}; use std::path::Path; use std::io::Write; fn main() -> std::io::Result<()> { // Set up custom temp directory at startup let custom_temp = "/var/cache/myapp/temp"; std::fs::create_dir_all(custom_temp)?; env::override_temp_dir(Path::new(custom_temp))?; // Now all default tempfile() calls use our custom directory let mut file = tempfile_in(custom_temp)?; writeln!(file, "Temporary data")?; // Verify where it was created assert!(env::temp_dir().starts_with("/var/cache/myapp/temp")); Ok(()) } ``` -------------------------------- ### Create and Write to a Simple Temporary File Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/INDEX.md Use `tempfile()` to create a temporary file that is automatically cleaned up when it goes out of scope. Ensure `std::io::Write` is in scope for `writeln!`. Returns `io::Result`. ```rust use tempfile::tempfile; use std::io::Write; let mut file = tempfile()?; writeln!(file, "data")?; // Automatic cleanup ``` -------------------------------- ### Create a new NamedTempFile Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-namedtempfile-struct.md Creates a new named temporary file in the default temporary directory. Returns an io::Error if file creation fails. ```rust use tempfile::NamedTempFile; let file = NamedTempFile::new()?; println!("Temp file at: {:?}", file.path()); # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Handling Different Tempfile Error Kinds Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/QUICK_REFERENCE.md Illustrates how to handle different kinds of I/O errors that can occur during temporary file creation. It uses `e.kind()` to match against specific `io::ErrorKind` variants, allowing for tailored error management. ```rust use std::io; match tempfile::tempfile() { Ok(f) => { /* use */ }, Err(e) => match e.kind() { io::ErrorKind::PermissionDenied => { println!("No permission"); }, io::ErrorKind::Io => { println!("Disk error"); }, _ => println!("Other error"), } } ``` -------------------------------- ### Builder::permissions() Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-builder-struct.md Sets explicit file or directory permissions. ```APIDOC ## Builder::permissions() ### Description Set file/directory permissions explicitly. ### Method `&mut self` ### Parameters #### Path Parameters - **permissions** (`Permissions`) - Required - `std::fs::Permissions` object ### Platform Notes - **Unix:** Permissions are affected by the umask. Actual permissions = requested & !umask - **Windows:** Read-only flag is respected; other bits are ignored - **WASI:** Permissions are ignored (platform has no permission model) ### Default 0o600 for files, 0o777 for directories (before umask) ### Example (Unix): ```rust use tempfile::Builder; use std::os::unix::fs::PermissionsExt; let perms = std::fs::Permissions::from_mode(0o644); let file = Builder::new() .permissions(perms) .tempfile()?; # Ok::<(), std::io::Error>(()) ``` ``` -------------------------------- ### Configure Temporary File Creation with Builder Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/configuration.md Use the Builder struct to customize temporary file creation with options like prefix, suffix, random bytes, append mode, and permissions. Ensure the Builder is imported. ```rust use tempfile::Builder; use std::fs::Permissions; let file = Builder::new() .prefix("myapp-") .suffix(".log") .rand_bytes(8) .append(true) .tempfile()?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Handling Standard io::Error Kinds Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-errors.md Demonstrates how to match and handle different kinds of standard Rust io::Error returned by tempfile functions. ```rust use tempfile::tempfile; match tempfile() { Ok(f) => println!("Success"), Err(e) => { match e.kind() { std::io::ErrorKind::PermissionDenied => { println!("Permission denied"); }, std::io::ErrorKind::Io => { println!("Disk full or other I/O error"); }, _ => println!("Other error: {}", e), } } } ``` -------------------------------- ### tempdir() Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-builder-struct.md Creates a temporary directory in the default system location. This method is part of the Builder API. ```APIDOC ## tempdir() ### Description Create a temporary directory in the default location. ### Method This is a method call on a Builder instance. ### Returns `io::Result` ### Example ```rust use tempfile::Builder; let dir = Builder::new() .prefix("myapp-") .tempdir()?; # Ok::<(), std::io::Error>(()) ``` ``` -------------------------------- ### Create Temporary File (Most Secure) Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/QUICK_REFERENCE.md Creates a temporary file that is automatically deleted by the OS when closed or when the program exits. Ensure necessary imports and error handling. ```rust use tempfile::tempfile; let mut f = tempfile()?; write!(f, "data")?; // Auto-deleted by OS ``` -------------------------------- ### Create Temporary File in Current Directory Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-tempfile_in-function.md Demonstrates creating a temporary file in the current directory using `tempfile_in`. The file is automatically deleted by the OS when all handles are closed. Ensure necessary imports are present. ```rust use tempfile::tempfile_in; use std::io::Write; // Create temporary file in current directory let mut file = tempfile_in("./")?; writeln!(file, "Data in current directory")?; // File is automatically cleaned up # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Persistence and Cleanup Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/INDEX.md Methods for managing the lifecycle of temporary files, including persisting them to a final location, keeping them, or explicitly closing and deleting them. ```APIDOC ## Persistence and Cleanup ### `persist(path: &Path)` **Description**: Moves the temporary file to the specified final location. Returns the file handle if successful or an error. ### `persist_noclobber(path: &Path)` **Description**: Persists the temporary file to the specified final location only if the target path does not already exist. Returns the file handle if successful or an error. ### `keep()` **Description**: Prevents the temporary file or directory from being automatically deleted upon closing. Returns the path of the kept file/directory. ### `close()` **Description**: Explicitly closes and deletes the temporary file or directory. Returns an `io::Result<()>` to indicate success or failure of the deletion. ### `disable_cleanup(disable: bool)` **Description**: Controls whether automatic cleanup (deletion) occurs when the temporary file or directory is closed or goes out of scope. Setting `disable` to `true` prevents automatic deletion. ### `reopen()` **Description**: Creates another independent file handle to the same temporary file. This is useful when you need multiple independent access points to the same temporary file. ``` -------------------------------- ### TempDir::with_prefix() Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-tempdir-struct.md Creates a new temporary directory with a specified name prefix in the system's default temporary location. The directory and its contents are automatically deleted when the TempDir value is dropped. ```APIDOC ## TempDir::with_prefix() ### Description Creates a temporary directory with a specific name prefix in the default system temp location. The directory and its contents are automatically deleted when the `TempDir` is dropped. ### Signature ```rust pub fn with_prefix>(prefix: S) -> io::Result ``` ### Parameters #### Path Parameters - **prefix** (`S` where `S: AsRef`) - Required - The prefix for the temporary directory name. ### Returns `io::Result` - A `TempDir` instance on success, or an `io::Error` if creation fails. ### Example ```rust use tempfile::TempDir; let dir = TempDir::with_prefix("build-")?; let name = dir.path().file_name().unwrap().to_str().unwrap(); assert!(name.starts_with("build-")); # Ok::<(), std::io::Error>(()) ``` ``` -------------------------------- ### make_in() Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-builder-struct.md Creates a temporary file-like object within a specified directory using a custom closure. This is useful when you need to control the location of the temporary file. ```APIDOC ## make_in() ### Description Create a file-like object in a specific directory. ### Parameters #### Path Parameters - `dir` (P) - Required - Directory path for the temporary file - `f` (F) - Required - Closure that takes a path and returns `io::Result` ### Request Example ```rust use tempfile::Builder; use std::os::unix::net::UnixListener; let tempsock = Builder::new().make_in("./", |path| { UnixListener::bind(path) })?; # Ok::<(), std::io::Error>(()) ``` ``` -------------------------------- ### Create Temporary Directory Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/QUICK_REFERENCE.md Creates a temporary directory that is automatically deleted when the `Dir` object is dropped. Useful for grouping temporary files. ```rust use tempfile::tempdir; let dir = tempdir()?; let path = dir.path().join("file.txt"); // Auto-deleted when dir dropped ``` -------------------------------- ### Thread-Safe Temporary File Creation Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/configuration.md Demonstrates the thread-safe nature of creating temporary files using `NamedTempFile::new()` from multiple threads concurrently. This is safe because `Builder` is Send + Sync and configuration overrides use thread-safe mechanisms like `OnceLock`. ```rust use tempfile::NamedTempFile; use std::thread; let handles: Vec<_> = (0..10).map(|_| { thread::spawn(|| { // Safe to use from multiple threads NamedTempFile::new() }) }).collect(); for h in handles { let _ = h.join(); } ``` -------------------------------- ### Builder Type Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/DOCUMENTATION_MANIFEST.md Details on the Builder type for configuring temporary file and directory creation, including configuration options and creation methods. ```APIDOC ### Builder — Configuration builder - Configuration: `prefix()`, `suffix()`, `rand_bytes()`, `append()`, `permissions()`, `disable_cleanup()` - Creation: `tempfile()`, `tempfile_in()`, `tempdir()`, `tempdir_in()`, `make()`, `make_in()` ``` -------------------------------- ### Create Named Temporary File Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/api-builder-struct.md Use `tempfile()` to create a named temporary file in the default temporary directory. You can specify a prefix and suffix for the filename. ```rust use tempfile::Builder; let file = Builder::new() .prefix("app-") .suffix(".tmp") .tempfile()?; # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Essential Imports for Tempfile Source: https://github.com/stebalien/tempfile/blob/master/_autodocs/QUICK_REFERENCE.md Import necessary functions and types for creating temporary files, directories, and spooled files. Also includes imports for error types and configuration builders. ```rust use tempfile::{ tempfile, tempfile_in, // Anonymous files tempdir, tempdir_in, // Directories spooled_tempfile, // In-memory→disk spooled_tempfile_in, Builder, // Configuration NamedTempFile, TempDir, TempPath, // Types SpooledTempFile, SpooledData, // Spooled types env, // Configuration }; // Error types use tempfile::{PersistError, PathPersistError}; ```