std-type

File: open handle to a file

A File is an owned OS handle with access determined at opening. It implements byte I/O; opening an existing file for reading is different from creating it. Run only inside a disposable working directory. The fixture must not already exist. Expected stdout (not executed): tea Common mistake: Assuming opening a file reads the entire file.

Formal Syntax & Structure

rust syntaxrust
File::open(path) -> io::Result<File>

Working Example

Example Snippetrust
fn main() {    use std::fs::{self, File, OpenOptions};    use std::io::{Read, Write};    fs::create_dir("bm-fixture").expect("use a fresh disposable directory");    let p = std::path::Path::new("bm-fixture").join("note.txt");    File::create_new(&p).unwrap().write_all(b"tea").unwrap();    let mut f = File::open(&p).unwrap();    let mut s = String::new();    f.read_to_string(&mut s).unwrap();    println!("{s}");}
Rust Reference