Files and path handling
Quick answer
Path describes a borrowed operating-system path and PathBuf owns one. Use path operations instead of concatenating separators by hand. File operations are fallible, and a path does not prove that the target exists or that access is permitted.
Build paths and open safely
join appends a relative path, but an absolute path can replace the base; it does not enforce containment. Validate untrusted components and use a stronger filesystem boundary when necessary. OpenOptions::create_new(true) avoids overwriting an existing file. File closes on drop; explicit synchronization is needed when durability matters.
use std::path::PathBuf;fn main() { let path = PathBuf::from("reports").join("today.txt"); println!("{}", path.file_name().unwrap().to_str().unwrap()); println!("{}", path.extension().unwrap().to_str().unwrap()); }Expected stdout (not executed):
today.txttxtThe example inspects components rather than platform separators.
use std::{fs::{self, OpenOptions}, io::{self, Write}};fn main() -> io::Result<()> { let mut file = OpenOptions::new().write(true).create_new(true).open("report.txt")?; file.write_all(b"ready")?; drop(file); println!("{}", fs::read_to_string("report.txt")?); Ok(()) }Expected stdout (not executed):
readyRun only in a fresh disposable working directory; the fixture runner removes its own directory.
Common mistake
File::create can truncate an existing file; avoid it when preserving content matters.
Try it yourself
Change the filename to summary.txt and explain what create_new does if the file already exists.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Files and path handling — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A new report must never overwrite an existing report. Which open option fits?
Files and path handling — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::path::PathBuf; fn main() { let path = PathBuf::from("reports").join("today.txt"); println!("{}", path.file_name().unwrap().to_str().unwrap()); println!("{}", path.extension().unwrap().to_str().unwrap()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Files and path handling — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::{fs::{self, OpenOptions}, io::{self, Write}}; fn main() -> io::Result<()> { let mut file = OpenOptions::new().write(true).create_new(true).open("report.txt")?; file.write_all(b"ready")?; drop(file); println!("{}", fs::read_to_string("report.txt")?); Ok(()) } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.