OpenOptions Read Write In Place
Open one handle with both read(true) and write(true), seek to a fixed record offset, and overwrite bytes in place without recreating the file.
Code
use std::fs::OpenOptions;
use std::io::{Read, Seek, SeekFrom, Write};
fn main() -> std::io::Result<()> {
let path = "state.bin";
{
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(path)?;
// 固定 16 字节一条的记录:槽位空闲时占位符也在原位
file.write_all(b"slot0:free \n")?;
file.write_all(b"slot1:reserved \n")?;
}
// 读写模式重开:先定位再覆盖,文件其余字节保持原样
let mut file = OpenOptions::new().read(true).write(true).open(path)?;
file.seek(SeekFrom::Start(6))?;
file.write_all(b"occupied")?;
file.seek(SeekFrom::Start(0))?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
for line in contents.lines() {
println!("line: [{}]", line.trim_end());
}
std::fs::remove_file(path)?;
Ok(())
}Inside the snippet
All of the logic lives in the function main.
The file repeats itself only inside for line in contents.lines(). Fallible operations return Result, and the ? operator short-circuits errors up to the caller.
Watch out for
- Where imports appear, they all name standard-library modules.
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Using it
The entry-point signature is fn main() -> std::io::Result<()>
The file’s steps show up in the output as line: [.
Key statements
let mut file = OpenOptions::new().read(true).write(true).open(path)?;
file.write_all(b"slot0:free \n")?;
file.write_all(b"slot1:reserved \n")?;
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Does the snippet panic on failure?
- As data, not exceptions: `Result` makes the caller handle both arms.
- What does OpenOptions Read Write In Place print when run?
- The script runs standalone; its 1 labeled outputs include `line: [`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.