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.
Code
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.
Resultis the only error channel — remove a?while adapting and that site needs an explicitmatch.
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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.