On this page
File
Prev: io_and_fs | Up: io_and_fs | Next: `BufReader`
Rel: io_and_fs, rust/builtins
Ref: Rust std — File
Tags: #public #prog #rust #stdlib #io_and_fs #tier/core
Signature & Overview
std::fs::File /* + std::fs::read_to_string */
OS file handle implementing Read and Write, automatically closed on Drop.
Notes & Pitfalls
- Unbuffered by default: Wrap in
BufReader/BufWriterfor repeated small reads/writes, or usestd::fs::read_to_string/std::fs::writefor whole small files. - Closes automatically on
Drop: Call.sync_all()if you need durability guarantees before returning.
Example
use std::fs;
use std::io::Write;
fn main() -> std::io::Result<()> {
let path = std::env::temp_dir().join("rust_file_demo.txt");
{
let mut f = fs::File::create(&path)?;
writeln!(f, "hello rust")?;
}
assert_eq!(fs::read_to_string(&path)?.trim(), "hello rust");
fs::remove_file(path)?;
Ok(())
}
Linked from
Related notes
- tuts/rust/std/io_and_fs/BufReader Linked here; links to this page; shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/io_and_fs Linked here; links to this page; shared tags: #prog, #rust, #stdlib
- tuts/rust/builtins Linked here; shared tags: #prog, #rust
- tuts/rust/std/collections/BinaryHeap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/BTreeMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashSet shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/VecDeque shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/error_and_fmt/Display shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/error_and_fmt/Error shared tags: #prog, #rust, #stdlib, #tier