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

68 views Asked by At

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.

2

There are 2 answers

0
Jim Lewis On BEST ANSWER

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.

0
sashank On
  1. It depends on the owner of the process who runs the program, whether the owner has permissions to write to that directory or not. For example, apache running as www user may not be able to write to a directory owned by root and no permissions for other or group.

  2. You may do it hit or trail way, like try creating the file to see if it's successful or not, in case it fails to catch the proper error code and like no permission or directory full and take corrective action.

  3. You may programmatically check if the user has permissions to write into directory if the directory has space, if the file already exists etc. By using certain apis the system exposes and the language exposes, this much better approach taking care of cases rather than handling failure cases.