【问题标题】:Create a temporary directory in Haskell在 Haskell 中创建一个临时目录
【发布时间】:2010-06-04 22:31:34
【问题描述】:

在 Haskell 中安全地创建临时目录的正确方法是什么? System.IO 提供了创建临时文件 的方法,但我找不到任何对目录执行相同操作的方法,无论是在目录中还是在System.DirectorySystem.Posix.DirectorySystem.Posix.Temp 中。有没有我忽略的功能,还是我需要自己写一个? (如果是这样,是否有任何危险需要避免,例如创建临时文件?)

【问题讨论】:

    标签: haskell temporary-directory


    【解决方案1】:

    为了专门用于 Unix 系统,Unixutils 包包含这样一个函数:

    withTemporaryDirectory :: FilePath -> (FilePath -> IO a) -> IO a

    如果您需要它同时在 Windows 和 Unix 系统上工作,您将希望使用临时包来代替。它具有相同的功能,但类型签名略有不同:

    withTemporaryDirectory :: FilePath -> String -> (FilePath -> IO a) -> IO a

    【讨论】:

    • 这将返回将创建新临时文件的目录(即通常为“/tmp”)。它实际上并没有创建一个临时目录。
    • @Travis 确认! withTemporaryDirectory 是我要找的。​​span>
    • 这很符合我的想法,因为它会在我完成后自动清理目录。
    • 请注意,temporary 软件包在 hackage 上具有许多类似的功能。 (是的,这已经晚了一年,但这个问题很容易在 Google 搜索中出现)
    • @ThomasM.DuBuisson 您应该将此作为答案重新发布,因为它似乎更合适,因为它与平台无关。
    【解决方案2】:

    您可以查看 Cabal 源的 Distribution.Compat.TempFile 模块作为示例。它将createTempDirectory 定义如下(其中c_getpidmkPrivateDir 是特定于平台的):

    createTempDirectory :: FilePath -> String -> IO FilePath
    createTempDirectory dir template = do
      pid <- c_getpid
      findTempName pid
      where
        findTempName x = do
          let dirpath = dir </> template ++ show x
          r <- try $ mkPrivateDir dirpath
          case r of
            Right _ -> return dirpath
            Left  e | isAlreadyExistsError e -> findTempName (x+1)
                    | otherwise              -> ioError e
    

    Cabal 定义了这个函数的事实表明没有标准的方法来做到这一点。

    【讨论】:

    • 此功能现已被分解到 temporary 包中。
    【解决方案3】:

    根据@Nikita Volkov 的建议,我将@Thomas M. DuBuisson 的评论作为单独的答案发布:

    使用temporary 包。它为使用临时文件和目录提供了一个方便的独立于平台的 API。临时文件和目录在使用后会自动删除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-18
      • 2017-03-06
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      相关资源
      最近更新 更多