mar*_*rds 8 filesystems io haskell
我想知道如何以最少的开销获取haskell中文件的大小.现在我有以下代码:
getFileSize :: FilePath -> IO Integer
getFileSize x = do
handle <- openFile x ReadMode
size <- hFileSize handle
hClose handle
return size
Run Code Online (Sandbox Code Playgroud)
这似乎很慢.我偶然发现了System.Posix.Files中的getFileStatus,但不知道它是如何工作的 - 至少我在ghci中玩它时只会遇到错误.另外,我不确定这是否适用于Windows(可能不适用).
重申一下:在Haskell中获取文件大小的最佳(和平台无关)方法是什么?
Ken*_*kot 12
你想要的确是什么,getFileStatus并且fileSize都来自System.Posix(在Windows下可以正常工作,请注意).用法如下,让错误处理由你决定:
getFileSize :: String -> IO FileOffset
getFileSize path = do
stat <- getFileStatus path
return (fileSize stat)
Run Code Online (Sandbox Code Playgroud)
对于它的价值,虽然我认为它的可读性较差,但您可以将此表格缩短为:
getFileSize path = getFileStatus path >>= \s -> return $ fileSize s
Run Code Online (Sandbox Code Playgroud)
我不知道是否有更好的方法.RWH提供它自己的包装,以hFileSize:
getFileSize path = handle (\_ -> return Nothing) $
bracket (openFile path ReadMode) hClose $ \h -> do
size <- hFileSize h
return (Just size)
Run Code Online (Sandbox Code Playgroud)
它还指出unix-compat是可用的,它"提供了unix软件包部分的可移植实现".