File System Operations
File Permissions
std::fs::Permissions represents the access-control permissions of a file or directory. To stay portable across all operating systems, the core Permissions struct exposes a universal .readonly() / .set_readonly(bool) interface, while full POSIX 9-bit octal mode permissions (rwxr-xr-x, 0o755, 0o600) are unlocked through std::os::unix::fs::PermissionsExt.
Reading and Modifying Permissions
Note that modifying a Permissions value in memory (perms.set_readonly(true) or perms.set_mode(0o600)) does not change the file on disk until you apply it using fs::set_permissions(path, perms) or file.set_permissions(perms):
Two-Step Permission Update Flow:
1. Obtain or construct `Permissions`:
`let mut perms = file.metadata()?.permissions();`
(or on Unix: `let perms = Permissions::from_mode(0o600);`)
2. Mutate & apply to the filesystem:
`perms.set_readonly(true);`
`file.set_permissions(perms)?;` (or `fs::set_permissions(path, perms)?;`)
| Operation | Cross-Platform API (std::fs) |
Unix Extension API (std::os::unix::fs::PermissionsExt) |
|---|---|---|
| Check read-only | perms.readonly() -> bool |
perms.mode() & 0o222 == 0 |
| Toggle read-only | perms.set_readonly(bool) |
— |
| Read full octal mode | — | perms.mode() -> u32 (mask with & 0o7777 for permission bits) |
| Set exact octal mode | — | perms.set_mode(0o600) or Permissions::from_mode(0o600) |
Apply to open File |
file.set_permissions(perms)? |
file.set_permissions(Permissions::from_mode(0o600))? |
| Apply by path | fs::set_permissions(path, perms)? |
fs::set_permissions(path, Permissions::from_mode(0o600))? |
Cross-Platform and Unix Octal Permission Example
use std::fs::{self, File};
use std::io;
fn main() -> io::Result<()> {
let path = std::env::temp_dir().join("rust_ch50_perms_demo.key");
let file = File::create(&path)?;
// 1. Cross-platform `.readonly()` and `.set_readonly(true)`:
let mut perms = file.metadata()?.permissions();
println!("initial readonly: {}", perms.readonly());
perms.set_readonly(true);
file.set_permissions(perms)?;
println!(
"after set_readonly(true): {}",
fs::metadata(&path)?.permissions().readonly()
);
// 2. On Unix, set exact octal mode `0o600` (owner read/write only):
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
file.set_permissions(fs::Permissions::from_mode(0o600))?;
let mode = file.metadata()?.permissions().mode() & 0o777;
println!("unix octal mode: {:04o}", mode);
}
// Ensure writable on Windows before removing:
#[cfg(windows)]
{
let mut p = file.metadata()?.permissions();
p.set_readonly(false);
file.set_permissions(p)?;
}
drop(file);
fs::remove_file(&path)?;
Ok(())
}
initial readonly: false
after set_readonly(true): true
unix octal mode: 0600