Reputation: 983
I was wondering if there is a way to check if the rust application has permission to write inside a folder?
I saw there was a way to check it by reading the raw bits permission, but this doesn't take the user or group into account. Another way could be to write a file and see if it fails, but that doesn't sound very elegant.
So far I have tried this, but it seems like it only works for files (?)
use std::fs::File;
fn main() {
let loc = "/var/log/myfolder";
// Check if able to write inside directory
let res = File::options()
.read(false)
.write(true)
.open(loc);
if res.is_ok() {
println!("No read permission");
} else {
println!("Read permission");
}
}
Is there a simpler way to check if a folder has write permissions without trying to create a file inside it?
Upvotes: 1
Views: 2599
Reputation: 6651
You can use fs::metadata
:
use std::fs;
fn main() -> std::io::Result<()> {
let loc = "/etc/";
// Check if able to write inside directory
let md = fs::metadata(loc)?;
let permissions = md.permissions();
let readonly = permissions.readonly();
if readonly {
println!("No write permission");
} else {
println!("Write permission");
}
Ok(())
}
On a Unix-like system you can get more specific information with the PermissionsExt
trait:
use std::fs;
// make sure to import the trait
use std::os::unix::fs::PermissionsExt;
fn main() -> std::io::Result<()> {
let loc = "/etc/";
// Check if able to write inside directory
let md = fs::metadata(loc)?;
let permissions = md.permissions();
let mode = permissions.mode();
println!("{:o}", mode); // 40755
Ok(())
}
Upvotes: 4