在 Haskell 中创建临时目录
在 Haskell 中安全创建临时目录的正确方法是什么? System.IO 提供了创建临时文件的方法,但我找不到任何对目录执行相同操作的方法,无论是在目录中还是在 System.Directory 中code>、System.Posix.Directory
或 System.Posix.Temp
。是否有一个我忽略的函数,或者我需要自己编写一个函数? (如果是这样,是否有任何需要避免的危险,就像创建临时文件一样?)
What is the proper way to safely create a temporary directory in Haskell? System.IO
offers ways to create temporary files, but I can't find anything that does the same for directories, neither there nor in System.Directory
, System.Posix.Directory
, nor System.Posix.Temp
. Is there a function I'm overlooking, or do I need to write one myself? (And if so, are there any dangers to avoid, like there are with creating temporary files?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了专门与 Unix 系统一起工作,Unixutils 包包含这样一个函数:
withTemporaryDirectory :: FilePath -> (文件路径->IO a)-> IO a
如果您需要它同时在 Windows 和 Unix 系统上工作,您将需要使用临时包。它具有相同的功能,但类型签名略有不同:
withTemporaryDirectory :: FilePath ->字符串 -> (文件路径 -> IO a) -> IO a
For working specifically with Unix systems, the Unixutils package contains such a function:
withTemporaryDirectory :: FilePath -> (FilePath -> IO a) -> IO a
If you need it to work on both Windows and Unix systems, you'll want to use the temporary package instead. It has the same function with a slightly different type signature:
withTemporaryDirectory :: FilePath -> String -> (FilePath -> IO a) -> IO a
您可以查看 Cabal 源代码的
Distribution.Compat.TempFile
模块作为示例。它定义createTempDirectory
如下(其中c_getpid
和mkPrivateDir
是特定于平台的):Cabal 定义此函数的事实表明没有标准方法来做到这一点。
You could look at the
Distribution.Compat.TempFile
module of the Cabal source for an example. It definescreateTempDirectory
as follows (wherec_getpid
andmkPrivateDir
are platform-specific):The fact that Cabal defines this function suggests that there's not a standard way to do it.
根据 @Nikita Volkov 的建议,我将 @Thomas M. DuBuisson 的评论作为单独的答案发布:
使用 临时包。它提供了一个方便的独立于平台的 API,用于使用临时文件和目录。临时文件和目录在使用后会自动删除。
As suggested by @Nikita Volkov, I am posting the comment of @Thomas M. DuBuisson as a separate answer:
Use the temporary package. It provides a convenient platform-independent API for using temporary files and directories. The temporary files and directories are automatically deleted after use.