pub struct TempFile { /* private fields */ }
Expand description
The path of an existing writable file in a system temporary directory.
Deletes the file on drop. Ignores errors deleting the file.
§Example
use temp_file::TempFile;
let t = TempFile::new()
.unwrap()
.with_contents(b"abc")
.unwrap();
// Prints "/tmp/1a9b0".
println!("{:?}", t.path());
assert_eq!(
"abc",
std::fs::read_to_string(t.path()).unwrap(),
);
// Prints "/tmp/1a9b1".
println!("{:?}", TempFile::new().unwrap().path());
Implementations§
Source§impl TempFile
impl TempFile
Sourcepub fn with_prefix(prefix: impl AsRef<str>) -> Result<Self, Error>
pub fn with_prefix(prefix: impl AsRef<str>) -> Result<Self, Error>
Create a new empty file in a system temporary directory.
Use prefix
as the first part of the file’s name.
Drop the returned struct to delete the file.
§Errors
Returns Err
when it fails to create the file.
§Example
// Prints "/tmp/ok1a9b0".
println!("{:?}", temp_file::TempFile::with_prefix("ok").unwrap().path());
Sourcepub fn with_suffix(suffix: impl AsRef<str>) -> Result<Self, Error>
pub fn with_suffix(suffix: impl AsRef<str>) -> Result<Self, Error>
Create a new empty file in a system temporary directory.
Use suffix
as the last part of the file’s name.
You can use this to give the filename a particular extension.
Drop the returned struct to delete the file.
§Errors
Returns Err
when it fails to create the file.
§Example
// Prints "/tmp/1a9b0.txt".
println!("{:?}", temp_file::TempFile::with_suffix(".txt").unwrap().path());
Sourcepub fn with_contents(self, contents: &[u8]) -> Result<Self, Error>
pub fn with_contents(self, contents: &[u8]) -> Result<Self, Error>
Sourcepub fn cleanup(self) -> Result<(), Error>
pub fn cleanup(self) -> Result<(), Error>
Remove the file now. Do nothing later on drop.
§Errors
Returns an error if the file exists and we fail to remove it.
Sourcepub fn panic_on_cleanup_error(self) -> Self
pub fn panic_on_cleanup_error(self) -> Self
Make the struct panic on drop if it hits an error while removing the file.