如果根据正常的程序操作和给定的用户输入预期文件在那里,则使用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");
Run Code Online (Sandbox Code Playgroud)
请注意,使用2可能会导致程序中出现安全问题.例如,如果文件在程序检查文件是否存在时出现,但在尝试打开文件时消失,则程序可能会以意外的方式运行.如果使用2,请确保程序仍然以理想的方式运行,如果打开文件失败,即使您的程序刚检查该文件是否存在且可读.