在D中打开一个文件 [英] Open a File in D

查看:138
本文介绍了在D中打开一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想安全地尝试在D中打开文件,则是首选的方式。

If I want to safely try to open a file in D, is the preferred way to either


  1. 尝试打开它,捕获异常(并且可选地找出原因)如果失败或

  2. 检查是否存在,可读,然后只打开它

我猜想第二个替代结果是更多的IO,更复杂吗?

I'm guessing the second alternative results in more IO and is more complex right?

推荐答案

通常情况下,最好检查文件是否存在,因为文件通常很可能不存在,并且简单地让它失败,当你尝试打开它是一个例外使用例外流量控制。在文件不存在的情况下也是低效的,因为D中的异常非常昂贵(尽管I / O的成本可能会超过给定I / O昂贵的异常的成本)。

Generally, it's better to check whether the file exists first, because it's often very likely that the file doesn't exist, and simply letting it fail when you try and open it is a case of using exceptions for flow control. It's also inefficient in the case where the file doesn't exist, because exceptions are quite expensive in D (though the cost of the I/O may still outweigh the cost of the exception given how expensive I/O is).

在异常可能被抛出的情况下,通常认为使用异常是不利的做法。在这些情况下,返回操作是否成功还是检查操作是否可能在尝试操作之前成功是好的。在打开文件的情况下,您可能会做后者。所以,最干净的方法来做你想要做的事情就是做一些像

It's generally considered bad practice to use exceptions in cases where the exception is likely to be thrown. In those cases, it's far better to return whether the operation succeeded or to check whether the operation is likely to succeed prior to attempting the operation. In the case of opening files, you'd likely do the latter. So, the cleanest way to do what you're trying to do would be to do something like

if(filename.exists)
{
    auto file = File(filename);
    ...
}

或者如果要阅读整个文件在一个字符串中,你会做

or if you want to read the whole file in as a string in one go, you'd do

if(filename.exists)
{
    auto fileContents = readText(filename);
    ...
}

code>和 readText 在std.file中,文件在std.stdio中。

exists and readText are in std.file, and File is in std.stdio.

如果您处理的文件很可能存在的情况,因此不太可能会抛出异常,然后跳过检查,只是尝试打开文件是罚款。但是,您希望避免的是依赖异常,因为它不是不会使操作失败。您希望异常很少被抛出,所以您检查这些操作是否会在尝试之前成功,如果可能会失败并抛出异常。否则,您最终会使用例外来进行流量控制,并损害程序的效率(和可维护性)。

If you're dealing with a case where it's highly likely that the file will exist and that therefore it's very unlikely that an exception will be thrown, then skipping the check and just trying to open the file is fine. But what you want to avoid is relying on the exception being thrown when it's not unlikely that the operation will fail. You want exceptions to be thrown rarely, so you check that operations will succeed before attempting them if it's likely that they will fail and throw an exception. Otherwise, you end up using exceptions for flow control and harm the efficiency (and maintainability) of your program.

通常情况下,文件不会在那里当您尝试打开它时,通常情况下您应该检查文件是否存在,然后再尝试打开它(但最终取决于您的具体用例)。

And it's often the case that a file won't be there when you try and open it, so it's usually the case that you should check that a file exists before trying to open it (but it does ultimately depend on your particular use case).

这篇关于在D中打开一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆