Haskell - 检查文件句柄的有效性

发布于 2024-11-04 18:34:58 字数 214 浏览 9 评论 0原文

好吧,伙计们,超级简单的问题(谷歌没有帮助我解决这个问题似乎很奇怪):

import IO

--.... yadda, yadda, yadda

  file <- openFile "/some/path" ReadMode

如何检查从 openFile 获得的句柄是否是有效的句柄,即文件存在并且打开成功?

Ok, guys, super easy question (it seems weird that Google didn't help me with this one):

import IO

--.... yadda, yadda, yadda

  file <- openFile "/some/path" ReadMode

How do I check if the handle that I got from openFile is a valid handle, i.e. that the file exists and was opened successfully?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

澜川若宁 2024-11-11 18:34:58

如果文件不存在,或者发生其他错误,对 openFile 的调用将失败并出现异常。

例如:

import System.IO

main = do
   openFile "/some/path" ReadMode

失败原因:

A.hs: /some/path: openFile: does not exist (No such file or directory)

openFile 可能抛出的异常类型 此处列出, 并包括:

  • isAlreadyInUseError 如果文件已打开且无法重新打开;
  • isDoesNotExistError 如果文件不存在; 则返回
  • 如果用户没有打开文件的权限,

isPermissionError 。您可以使用 Control.Exception< 捕获这些错误/a>,像这样:

{-# LANGUAGE ScopedTypeVariables #-}

import System.IO
import Control.Exception

main = do
    handle (\(e :: IOException) -> print e >> return Nothing) $ do
      h <- openFile "/some/path" ReadMode
      return (Just h)

If the file doesn't exist, or some other error occurs, the call to openFile will fail with an exception.

For example:

import System.IO

main = do
   openFile "/some/path" ReadMode

Fails with:

A.hs: /some/path: openFile: does not exist (No such file or directory)

The types of exception that may be thrown by openFile are listed here, and include:

  • isAlreadyInUseError if the file is already open and cannot be reopened;
  • isDoesNotExistError if the file does not exist; or
  • isPermissionError if the user does not have permission to open the file.

You can catch these errors using Control.Exception, like so:

{-# LANGUAGE ScopedTypeVariables #-}

import System.IO
import Control.Exception

main = do
    handle (\(e :: IOException) -> print e >> return Nothing) $ do
      h <- openFile "/some/path" ReadMode
      return (Just h)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文