exception - 在 D 中打开一个文件

标签 exception file-io d

如果我想安全地尝试在 D 中打开一个文件,这两种方式都是首选

  1. 尝试打开它,如果失败则捕获异常(并有选择地找出原因)
  2. 检查它是否存在,是否可读,然后才打开它

我猜第二种选择会导致更多 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/

相关文章:

ios - Cordova 写入 WWW 目录 (iOS)

d - 开始使用 vibe.d

licensing - 公共(public)领域还是无二进制归因 FFT Lib?

调用回调函数时出现C#异常

xamarin - 如何解决 Xamarin.Forms.Platform.Android.ListViewAdapter.IsEnabled 异常?

java - 当缓冲区已满时,DataOutputStream 会自动刷新吗?

python - 优化 bigint 调用

c# - 什么会导致 throw 重置调用堆栈(我使用的是 "throw",而不是 "throw ex")

Android,处理 SQLiteConstraintException

c# - 你如何读取正在使用的文件?