如果我想安全地尝试在 D 中打开一个文件,这两种方式都是首选
- 尝试打开它,如果失败则捕获异常(并有选择地找出原因)
- 检查它是否存在,是否可读,然后才打开它
我猜第二种选择会导致更多 IO 并且更复杂,对吗?
最佳答案
如果根据正常的程序操作和给定的用户输入,预计文件在那里,则使用 1 - 只尝试打开文件并依靠异常处理来处理文件不存在的异常情况。
例如:
/// If the user has a local configuration file in his home directory, open that.
/// Otherwise, open the global configuration file that is a part of the program,
/// and should be installed on all systems where the program is running.
File configFile;
if ("~/.transmogrifier.conf".expandTilde.exists)
configFile.open("~/.transmogrifier.conf".expandTilde);
else
configFile.open("/etc/transmogrifier.conf");
请注意,使用 2 可能会导致您的程序出现安全问题。例如,如果在您的程序检查文件是否存在时文件存在,但在尝试打开文件时文件消失了,则您的程序可能会出现意外行为。如果您使用 2,请确保您的程序在打开文件失败时仍然以理想的方式运行,即使您的程序只是检查文件存在且可读也是如此。
关于exception - 在 D 中打开一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18888354/