Set Len Preallocates Fixed Size

Preallocate fixed-size record files with File::set_len, which extends or truncates to the exact byte count and keeps len fully controlled.

RustData Integrity

Code

rustsnippet
23 lines
use std::fs::OpenOptions;
use std::io::Write;

fn main() -> std::io::Result<()> {
    let dir = std::env::temp_dir().join("set_len_demo");
    std::fs::create_dir_all(&dir)?;
    let path = dir.join("fixed.bin");

    let mut file = OpenOptions::new().write(true).create(true).truncate(true).open(&path)?;

    // set_len 把文件扩展到固定字节数:日志槽位、固定记录文件先定容量
    file.set_len(64)?;
    println!("after extend: {}", file.metadata()?.len());

    // 写入只落在开头,随后可再次收缩,len 始终精确可控
    file.write_all(b"payload")?;
    file.set_len(4)?;
    println!("after shrink: {}", file.metadata()?.len());

    std::fs::remove_file(&path).ok();
    std::fs::remove_dir_all(&dir).ok();
    Ok(())
}

Inside the code

The real workload lives in the function main — everything else is wiring.

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

Watch out for

  • The package manager never enters the picture for this snippet.
  • Result is the only error channel — remove a ? while adapting and that site needs an explicit match.

Putting it to use

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

Every step is announced in the output: after extend:, after shrink:.

Core lines

let mut file = OpenOptions::new().write(true).create(true).truncate(true).open(&path)?;
std::fs::create_dir_all(&dir)?;
file.write_all(b"payload")?;

Interactive Tools for This Topic

FAQ

What happens when a call fails?
Through the type system: failures are `Result` variants the caller must consume.
What does Set Len Preallocates Fixed Size print when run?
No setup needed: run the file and look for labeled lines like `after extend:`, `after shrink:` in the output.