How to test std::fs::File has write permission

Hi, rust experts.

I have an instance of std::fs::File, before I write to file, I need to test if File was opened with write permission.

Seems ioctl can be used for this in linux c, But I don't know how to do it in safe rust?

I don't know, but why don't you just try writing and see if you get an error?

1 Like

I think you can use std::fs::metadata ?
( and then Permissions in std::fs - Rust )

emm.. then it will need to handle different kind of system error to check if it was caused by "no permission" if just writing file without first check. :rofl:

Checking then writing is wrong, though. It introduces a TOCTOU race condition in your code. By the time you actually attempt to write to a supposedly-writeable file, it might have changed permissions in the meantime, leading to hard-to-reproduce and hard-to-debug errors.

Really, just try writing to the file and check if it failed. That's how you can do it properly, and it's shorter, too.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.