file-iofile-permissionsdirectory-permissions

How do I test whether I could write to a filename?


The title may seem trivial, but this isn't as easy as it sounds. You can't just check the permissions on the file, because the file may not exist, and you may have the necessary permissions to create it and then write to it. But only if you have write permissions on the directory, and maybe execute permissions, and maybe permissions for all the parent directories. Or maybe not. I'm not sure.

So, given a filename, what are all the cases that I need to account for in order to correctly test whether I could open and write to a file with that filename? This isn't specific to any one programming language. I just want the logic. But examples in real programming languages are welcome.


Solution

  • Such a test wouldn't necessarily be very useful -- you're just setting yourself up for a race condition, if the file becomes unwriteable for some reason between your check and the write attempt. (Some other process could change the permissions, move or delete the parent directory, use up the last free space on the device, etc...)

    I'd just go ahead and attempt the write, and be diligent about checking for errors at each step (opening, each write attempt, closing) where an operation could conceivably fail.