Created
August 17, 2012 23:04
-
-
Save alech/3383351 to your computer and use it in GitHub Desktop.
cat in haskell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import System.IO | |
import System.Environment | |
import Data.Maybe | |
import System.Directory | |
main :: IO () | |
main = do | |
hSetBuffering stdout NoBuffering | |
args <- getArgs | |
let files = case args of | |
[] -> [Nothing] | |
_ -> map (\f -> Just f) args | |
mapM_ cat files | |
-- if nothing, just cat stdin | |
cat :: Maybe FilePath -> IO () | |
cat file = do | |
exists <- case file of | |
Just f -> checkExists f | |
_ -> return True | |
readable <- if exists then | |
case file of | |
Just f -> checkReadable f | |
_ -> return True | |
else | |
return False | |
if exists && readable then do | |
handle <- maybe (return stdin) (\f -> openBinaryFile f ReadMode) file | |
c <- hGetContents handle | |
hSetBuffering handle NoBuffering | |
putStr c | |
else | |
return () | |
-- check if file exists | |
checkExists :: FilePath -> IO Bool | |
checkExists file = do | |
exists <- doesFileExist file | |
if not exists then do | |
hPutStrLn stderr $ "File does not exist: " ++ file | |
return False | |
else | |
return True | |
-- check if file is readable | |
checkReadable file = do | |
p <- getPermissions file -- this may fail when accessing permissions is not allowed :( | |
if not (readable p) then do | |
hPutStrLn stderr $ "File is not readable: " ++ file | |
return False | |
else | |
return True | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment