What is the best way to get the file size in haskell?

I am wondering how to get the file size 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 rather slow. I stumbled upon getFileStatus in System.Posix.Files, but I don’t know how it works - at least I get errors when playing with it in ghci. Also, I'm not sure if this will work on Windows (maybe not).

So to repeat: what is the best (and platform independent) approach to get file size in Haskell?

+8
source share
4 answers

Actually, you need getFileStatus and fileSize , both from System.Posix (which will work fine on Windows if you use the unix-compat package instead of unix ). Usage is as follows, leaving error handling to your discretion:

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

Why is it worth it, and although I think it is less readable, you can shorten this form to:

 getFileSize path = getFileStatus path >>= \s -> return $ fileSize s 
+12
source

I do not know if there is a better way. RWH ships its own wrapper in hFileSize:

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

He also notes that unix-compat is available, which "provides portable implementations of parts of the unix package."

+8
source

It seems that System.Posix.Files does not work on Windows (except Cygwin), have you tried to use unix-compat?

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

This worked on my windows 10 machine:

 > 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 
+1
source
 import System.Posix.Files import System.Posix.Types getFileSize :: FilePath -> IO FileOffset getFileSize path = fmap fileSize $ getFileStatus path 
+1
source

Source: https://habr.com/ru/post/885647/


All Articles