在haskell中检索文件大小的最佳方法是什么? [英] What is the best way to retrieve the size of a file in haskell?

查看:138
本文介绍了在haskell中检索文件大小的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am wondering how to get the size of a file in haskell with the least amount of overhead. Right now I have the following code:

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

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

This seems to be quite slow. I have stumbled across getFileStatus in System.Posix.Files but don't know how it works - at least I only get errors when playing around with it in ghci. Also, I am not sure if this would work on Windows (probably not).

所以要重申:什么是最好的(和平台无关的)方法来获得大小在Haskell中的一个文件?

So to reiterate: What is the best (and platform independent) approach to get the size of a file in Haskell?

推荐答案

你想要的确实是 getFileStatus fileSize ,它们都来自 System.Posix (在Windows下它可以正常工作,请注意)。用法如下,错误处理由您决定:

What you want are indeed getFileStatus and fileSize, both from System.Posix (which will work just fine under Windows, mind you). Usage is as follows, leaving error handling up to you:

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

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

For what it's worth, and though I think it's less readable, you could shorten this form to:

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

这篇关于在haskell中检索文件大小的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆