如何测试是否可以写入文件名?
标题可能看起来微不足道,但这并不像听起来那么容易。您不能只检查文件的权限,因为该文件可能不存在,并且您可能具有创建它然后写入它的必要权限。但前提是您对该目录具有写入权限,也许还有执行权限,也许还具有所有父目录的权限。或者也许不是。我不知道。
那么,给定一个文件名,为了正确测试是否可以打开并写入具有该文件名的文件,我需要考虑哪些情况?这并不特定于任何一种编程语言。我只想要逻辑。但欢迎使用真实编程语言的示例。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这样的测试不一定很有用——你只是在设置自己
对于竞争条件,如果文件在检查之间由于某种原因变得不可写
和写入尝试。 (其他一些进程可能会更改权限、移动或删除
父目录,用完设备上的最后一个可用空间,等等...)
我只是继续尝试写入,并勤于检查错误
在每个步骤(打开、每次写入尝试、关闭),操作可以想象
失败。
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.
这取决于运行该程序的进程的所有者,该所有者是否有权写入该目录。例如,以www用户身份运行的apache可能无法写入root拥有的目录,并且其他或组没有权限。
您可以按命中或跟踪方式执行此操作,例如尝试创建文件以查看是否成功,以防万一它无法捕获正确的错误代码,例如没有权限或目录已满,并采取纠正措施。
您可以以编程方式检查用户是否有权写入目录,如果目录有空间,文件是否已存在等。通过使用系统公开的某些 API 和语言公开,这种更好的方法可以更好地处理情况比处理失败情况更重要。
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.
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.
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.