std-method

File::try_clone: duplicate an open handle

Create another handle to the same open file. Reads, writes and seeks can affect both handles; it is not an independent copy of the contents. Use a fresh disposable working directory exclusively controlled by this program. Expected stdout (not executed): b Common mistake: Expecting cloned handles to have independent positions.

Formal Syntax & Structure

rust syntaxrust
file.try_clone() -> io::Result<File>

Working Example

Example Snippetrust
fn main() {    use std::fs::{self, File};    use std::io::{Read, Write};    fs::create_dir("bm-fixture").expect("fresh working directory required");    let p = std::path::Path::new("bm-fixture").join("note.txt");    use std::io::{Seek, SeekFrom};    File::create_new(&p).unwrap().write_all(b"abc").unwrap();    let mut a = File::open(&p).unwrap();    let mut b = a.try_clone().unwrap();    a.seek(SeekFrom::Start(1)).unwrap();    let mut byte = [0];    b.read_exact(&mut byte).unwrap();    println!("{}", byte[0] as char);}
Rust Reference