| 1 |
# tempfile |
| 2 |
|
| 3 |
[](https://crates.io/crates/tempfile) |
| 4 |
[](https://github.com/Stebalien/tempfile/actions/workflows/ci.yml?query=branch%3Amaster) |
| 5 |
|
| 6 |
A secure, cross-platform, temporary file library for Rust. In addition to creating |
| 7 |
temporary files, this library also allows users to securely open multiple |
| 8 |
independent references to the same temporary file (useful for consumer/producer |
| 9 |
patterns and surprisingly difficult to implement securely). |
| 10 |
|
| 11 |
[Documentation](https://docs.rs/tempfile/) |
| 12 |
|
| 13 |
## Usage |
| 14 |
|
| 15 |
Minimum required Rust version: 1.63.0 |
| 16 |
|
| 17 |
Add this to your `Cargo.toml`: |
| 18 |
|
| 19 |
```toml |
| 20 |
[dependencies] |
| 21 |
tempfile = "3" |
| 22 |
``` |
| 23 |
|
| 24 |
## Supported Platforms |
| 25 |
|
| 26 |
This crate supports all major operating systems: |
| 27 |
|
| 28 |
- Linux |
| 29 |
- Android |
| 30 |
- MacOS |
| 31 |
- Windows |
| 32 |
- FreeBSD (likely other BSDs but we don't have CI for them) |
| 33 |
- RedoxOS |
| 34 |
- Wasm (build and link only, Wasm doesn't have a filesystem) |
| 35 |
- WASI P1 & P2. |
| 36 |
|
| 37 |
However: |
| 38 |
|
| 39 |
- Android, RedoxOS, Wasm, and WASI targets all require the latest stable rust compiler. |
| 40 |
- WASI P1/P2 does not define a default temporary directory. You'll need to explicitly call `tempfile::env::override_temp_dir` with a valid directory or temporary file creation will panic on this platform. |
| 41 |
- WASI P1/P2 does not have file permissions. |
| 42 |
- You _may_ need to override the temporary directory in Android as well to point at your application's per-app cache directory. |
| 43 |
|
| 44 |
## Example |
| 45 |
|
| 46 |
```rust |
| 47 |
use std::fs::File; |
| 48 |
use std::io::{Write, Read, Seek, SeekFrom}; |
| 49 |
|
| 50 |
fn main() { |
| 51 |
// Write |
| 52 |
let mut tmpfile: File = tempfile::tempfile().unwrap(); |
| 53 |
write!(tmpfile, "Hello World!").unwrap(); |
| 54 |
|
| 55 |
// Seek to start |
| 56 |
tmpfile.seek(SeekFrom::Start(0)).unwrap(); |
| 57 |
|
| 58 |
// Read |
| 59 |
let mut buf = String::new(); |
| 60 |
tmpfile.read_to_string(&mut buf).unwrap(); |
| 61 |
assert_eq!("Hello World!", buf); |
| 62 |
} |
| 63 |
``` |