Handle Missing, Locked and Read-Only Files Gracefully With Rust std::fs
Match on io::ErrorKind to handle NotFound, PermissionDenied and read-only filesystems from Rust std::fs, and use File::try_lock to detect a locked file.

Reading and writing a file in Rust is the easy half. The half that decides whether your tool feels solid is what it does when the file is missing, owned by someone else, on a read-only mount or held by another process. This post is about that failure path. The happy path, with BufReader and BufWriter, is covered in the post on reading and writing files with std::fs, so here we assume you can already open a file and focus on the errors.
The examples use Rust 1.89 on Linux 6.12. One feature, File::try_lock, was stabilized in Rust 1.89, and the post says where it matters.
Every failure is an io::Error
All of std::fs returns io::Result<T>, so a failure is an io::Error. Two methods on it matter. kind() returns an io::ErrorKind, a portable category, and raw_os_error() returns the underlying errno when the error came from the operating system. Branch on kind() for decisions and keep raw_os_error() for the cases it cannot express. The [ErrorKind documentation](https://doc.rust-lang.org/std/io/enum.ErrorKind.html) lists every variant.
The four you will meet most often on Linux:
| Situation | errno | ErrorKind |
|---|---|---|
| Path does not exist | ENOENT | NotFound |
| No permission to open or write | EACCES or EPERM | PermissionDenied |
File already exists (with create_new) | EEXIST | AlreadyExists |
| Write to a read-only filesystem | EROFS | ReadOnlyFilesystem |
ReadOnlyFilesystem was stabilized in Rust 1.83. On older compilers the same error arrives as ErrorKind::Other and you have to look at raw_os_error().
Missing files: decide whether it is an error
A missing file is rarely an error in itself. A config file that does not exist usually means "use the defaults". Treat it that way explicitly, and leave every other failure as a real error.
use std::fs;
use std::io::{self, ErrorKind};
fn read_config(path: &str) -> io::Result<String> {
match fs::read_to_string(path) {
Ok(text) => Ok(text),
Err(e) if e.kind() == ErrorKind::NotFound => Ok(String::from("port = 8080\n")),
Err(e) => Err(e),
}
}
fn main() {
match read_config("/etc/mytool/missing.conf") {
Ok(text) => print!("{text}"),
Err(e) => eprintln!("cannot read config: {e}"),
}
}port = 8080The guard e.kind() == ErrorKind::NotFound catches only the missing-file case. A PermissionDenied still propagates, which is what you want: silently using defaults because the file is unreadable would hide a real problem.
A common mistake is to call Path::exists() first and then open the file. That is a race. The file can disappear or change between the two calls, and exists() also returns false for any error, including a permission failure, so it cannot tell a missing file from a hidden one. Open the file and handle the error. The standard library documentation for [Path::try_exists](https://doc.rust-lang.org/std/path/struct.Path.html#method.try_exists) says the same thing and offers a version that keeps the error.
Permission denied: say who and what
PermissionDenied is the error users hit most and understand least, because the message does not name the path. Add the path yourself when you report it.
use std::fs::File;
use std::io::ErrorKind;
fn main() {
let path = "/etc/shadow";
match File::open(path) {
Ok(_) => println!("opened {path}"),
Err(e) if e.kind() == ErrorKind::PermissionDenied => {
eprintln!("{path}: permission denied (run as a user that may read it)");
}
Err(e) => eprintln!("{path}: {e}"),
}
}/etc/shadow: permission denied (run as a user that may read it)That output assumes you run it as an ordinary user. As root the file opens. The bare io::Error says "Permission denied (os error 13)" and nothing else, so a tool that reports only that leaves the user guessing which of its ten files was the problem. Wrap errors with the path, either by formatting as above or by using a crate such as anyhow with .with_context.
Read-only filesystems: fail early or fall back
Opening a file for reading works on a read-only mount. The failure arrives when you open for writing, or when you write. With OpenOptions you can detect it at the open call.
use std::fs::OpenOptions;
use std::io::{self, ErrorKind};
fn open_for_append(path: &str) -> io::Result<std::fs::File> {
OpenOptions::new().create(true).append(true).open(path)
}
fn main() {
match open_for_append("/proc/version") {
Ok(_) => println!("writable"),
Err(e) if e.kind() == ErrorKind::ReadOnlyFilesystem => {
println!("read-only filesystem, skipping the log file");
}
Err(e) if e.kind() == ErrorKind::PermissionDenied => {
println!("not allowed to write here");
}
Err(e) => println!("other error: {e}"),
}
}not allowed to write hereThe path /proc/version is used only because it exists on every Linux system and refuses writes. On a procfs file the kernel returns EACCES to a non-root user for a write open, so the second arm runs, and your result can differ as root or on another kernel. On a truly read-only mount, the first arm runs. The lesson is to handle both arms, because users cannot tell you which one they will hit.
Keep two cases apart. A file with the read-only attribute (mode 0444) gives PermissionDenied for a non-root writer, not ReadOnlyFilesystem, because the filesystem itself is writable. And the check metadata.permissions().readonly() on Unix looks only at whether the write bits are all clear, so it does not tell you whether you, specifically, can write. Try the open and react.
Locked files: advisory locks and try_lock
Linux file locks are advisory. They stop only processes that also ask for the lock, so they are useful for coordination between your own programs, not for protecting a file from a stranger. Since Rust 1.89, File has lock, lock_shared, try_lock and try_lock_shared, plus unlock. The try variants return immediately instead of blocking, and they report a held lock with a dedicated error type, TryLockError::WouldBlock.
use std::fs::OpenOptions;
use std::fs::TryLockError;
fn main() -> std::io::Result<()> {
let file = OpenOptions::new()
.create(true)
.write(true)
.open("/tmp/mytool.lock")?;
match file.try_lock() {
Ok(()) => {
println!("lock acquired, doing the work");
file.unlock()?;
}
Err(TryLockError::WouldBlock) => {
println!("another instance holds the lock, exiting");
}
Err(TryLockError::Error(e)) => return Err(e),
}
Ok(())
}lock acquired, doing the workIf a second copy runs while the first holds the lock, it prints the WouldBlock message instead. The lock is released when the File is dropped or the process exits, so a crash cannot leave a stale lock the way a PID file can. That is the main reason to prefer this over a "does the lock file exist" check. On Linux, std implements these with flock(2); read the man page for the exact semantics, including the warning that flock locks on NFS behave differently from local ones. Before Rust 1.89 you need the fs2 or fs4 crate for the same calls.
A reusable error report
Pull the pieces into one function that turns an io::Error and a path into a message a user can act on.
use std::io::{self, ErrorKind};
fn explain(path: &str, e: &io::Error) -> String {
match e.kind() {
ErrorKind::NotFound => format!("{path}: no such file"),
ErrorKind::PermissionDenied => format!("{path}: permission denied"),
ErrorKind::ReadOnlyFilesystem => format!("{path}: filesystem is read-only"),
ErrorKind::AlreadyExists => format!("{path}: already exists"),
_ => format!("{path}: {e}"),
}
}
fn main() {
let e = io::Error::from(ErrorKind::NotFound);
println!("{}", explain("/var/data/db", &e));
}/var/data/db: no such fileWhen this advice does not apply
If a program needs strong guarantees, do not rely on advisory locks and kind() alone. Use a database or an atomic rename for data that must not tear, and write to a temporary file in the same directory before renaming. Those patterns are the subject of later posts in this series.
Writing safely when failure is possible
Handling errors on open is only half of it. A write can fail after a successful open, for example when the disk fills up or a network mount drops, and BufWriter can hide the failure until it flushes. Call flush() explicitly and check its result, because the implicit flush on drop swallows errors. For data you cannot afford to lose, write to a temporary file in the same directory, call sync_all(), and then fs::rename it over the target. A rename within one filesystem is atomic, so readers see either the old file or the new one and never a half-written file. That pattern also turns a failure into something recoverable: if any step errors, the original file is untouched and you can report exactly which step failed.


