Search code examples
haskellfilesystemsio

Faster alternatives to hFileSize to retrieve the size of a file in 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

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).

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


Solution

  • What you want are indeed getFileStatus and fileSize, both from System.Posix (which will work just fine under Windows, if you use the unix-compat package instead of unix). Usage is as follows, leaving error handling up to you:

    getFileSize :: String -> IO Integer
    getFileSize path = do
        stat <- getFileStatus path
        return $ fromIntegral (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