ファイルサイズの取得

元ネタ http://ja.doukaku.org/243/

module Main where
import IO
import System (getArgs)
import Maybe (fromMaybe)

getFileSize :: String -> IO (Maybe Integer)
getFileSize path = catch
  (bracket
    (openFile path ReadMode)
    hClose
    (\h -> hFileSize h >>= return . Just))
  (const $ return Nothing)

main = do
  files <- getArgs
  sizes <- mapM getFileSize files
  mapM_ putStrLn $ zipWith (\file size -> file ++ ": " ++ (show size)) files $ map (fromMaybe (-1)) sizes

ファイルサイズの取得に失敗したときには-1を表示する。


実行結果

% ghc 243.hs
% ./a.out a.out not-exist
a.out: 634404
not-exist: -1