File Try Clone Shared Offset

Duplicate a file handle with File::try_clone and observe that both handles advance one shared cursor instead of independent positions.

RustData Integrity

Code

rustsnippet
23 lines
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};

fn main() -> std::io::Result<()> {
    let path = std::env::temp_dir().join("try_clone_shared_cursor.txt");
    let mut file = File::create(&path)?;
    file.write_all(b"shared cursor demo")?;
    file.seek(SeekFrom::Start(0))?;

    // try_clone duplicates the handle, and both share one file cursor
    let mut duplicate = file.try_clone()?;
    let mut first = [0_u8; 6];
    file.read_exact(&mut first)?;
    println!("first read: {:?}", String::from_utf8_lossy(&first));

    // the duplicate continues from the same offset, not from byte zero
    let mut second = [0_u8; 6];
    duplicate.read_exact(&mut second)?;
    println!("second read: {:?}", String::from_utf8_lossy(&second));

    let _ = std::fs::remove_file(&path);
    Ok(())
}

What the code does

Everything happens inside the function main.

Result is the error channel: the caller receives the failure as a value instead of an exception.

Points of care

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.
  • Result is the only error channel — remove a ? while adapting and that site needs an explicit match.

Using it

The primary signature is fn main() -> std::io::Result<()>

Output lines are prefixed (first read:, second read:), making each step’s effect easy to spot.

Key statements

file.write_all(b"shared cursor demo")?;
let mut duplicate = file.try_clone()?;
let mut file = File::create(&path)?;

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
No panics — `Result` values carry the failure, and `?` forwards them to the caller.
What does File Try Clone Shared Offset print when run?
Run it as a complete program — the output lines carry labels such as `first read:`, `second read:`.