在haskell中检索文件大小的最佳方法是什么?

时间:2011-04-11 10:59:09

标签: haskell filesystems io

我想知道如何以最少的开销获取haskell中文件的大小。现在我有以下代码:

getFileSize :: FilePath -> IO Integer
getFileSize x = do
handle <- openFile x ReadMode
size <- hFileSize handle
hClose handle
return size

这似乎很慢。我偶然发现了System.Posix.Files中的getFileStatus,但不知道它是如何工作的 - 至少我在ghci中玩它时只会遇到错误。此外,我不确定这是否适用于Windows(可能不适用)。

重申:在Haskell中获取文件大小的最佳(和平台无关)方法是什么?

5 个答案:

答案 0 :(得分:10)

你想要的确是getFileStatusfileSize,都来自System.Posix(在Windows下可以正常使用,请注意)。用法如下,让错误处理由你决定:

getFileSize :: String -> IO FileOffset
getFileSize path = do
    stat <- getFileStatus path
    return (fileSize stat)

对于它的价值,虽然我认为它的可读性较差,但您可以将此表格缩短为:

getFileSize path = getFileStatus path >>= \s -> return $ fileSize s

答案 1 :(得分:8)

我不知道是否有更好的方法。 RWH为hFileSize提供了自己的包装器:

getFileSize path = handle (\_ -> return Nothing) $
  bracket (openFile path ReadMode) hClose $ \h -> do
    size <- hFileSize h
    return (Just size)

它还注意到unix-compat可用,它“提供了unix包部分的可移植实现。”

答案 2 :(得分:1)

import System.Posix.Files
import System.Posix.Types

getFileSize :: FilePath -> IO FileOffset
getFileSize path = fmap fileSize $ getFileStatus path

答案 3 :(得分:0)

看起来System.Posix.Files在Windows中不起作用(Cygwin除外),你试过unix-compat吗?

https://hackage.haskell.org/package/unix-compat-0.4.1.4/docs/System-PosixCompat-Files.html

这在我的Windows 10机器上对我有用:

> cabal install unix-compat
Resolving dependencies...
... lots of output, plus I had to put Cygwin on my path to make it build ...
> ghci
Prelude> import System.PosixCompat.Files
Prelude System.PosixCompat.Files> getFileStatus ".bashrc">>= \s -> return $ fileSize s
5764

答案 4 :(得分:0)