Share File Data With fs::hard_link
Create a hard link with fs::hard_link, confirm both paths share file data, then modify through one name and read the change.
Code
use std::fs;
use std::io::Write;
fn main() -> std::io::Result<()> {
let dir = std::env::temp_dir().join(format!("hard-link-{}", std::process::id()));
fs::create_dir_all(&dir)?;
let original = dir.join("data.txt");
let linked = dir.join("data-link.txt");
let mut file = fs::File::create(&original)?;
file.write_all(b"version one")?;
drop(file);
// hard_link 不复制字节:两个路径指向同一份文件数据
fs::hard_link(&original, &linked)?;
let a = fs::metadata(&original)?.len();
let b = fs::metadata(&linked)?.len();
println!("sizes: {a} == {b}: {}", a == b);
// 通过链接名追加,原名读取到同样内容
let mut append = fs::OpenOptions::new().append(true).open(&linked)?;
append.write_all(b" + patched")?;
drop(append);
println!("through original: {}", fs::read_to_string(&original)?);
// 删除一个名字后数据仍由另一个名字持有
fs::remove_file(&linked)?;
println!("survives unlink: {}", original.exists());
println!("still readable: {}", fs::read_to_string(&original)?.len());
fs::remove_dir_all(&dir)?;
Ok(())
}What the code does
Share File Data With fs::hard_link keeps everything in the function main.
Fallible operations return Result, and the ? operator short-circuits errors up to the caller.
What to watch for
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Applying it
The main signature reads fn main() -> std::io::Result<()>
The run emits 4 labeled sections — sizes:, through original:, survives unlink:, still readable: — one per step.
Statements that matter
let mut append = fs::OpenOptions::new().append(true).open(&linked)?;
let mut file = fs::File::create(&original)?;
fs::hard_link(&original, &linked)?;
Interactive Tools for This Topic
FAQ
- How do errors reach the caller?
- Each fallible operation returns `Result`; nothing is silently discarded.
- What does Share File Data With fs::hard_link print when run?
- Execute the whole file; each printed line is prefixed with a label like `sizes:`, `through original:`, `survives unlink:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.