codesnippets:filesystemioandstreams
This is an old revision of the document!
Filesystem IO and streams
- example:
- code
{-| Description : is to provides a generalised, abstract, and save interface to the files system. Copyright : (c) Jörg K.-H. W. Brüggmann, 2021 License : CC0 1.0 Universal Maintainer : ...@... Stability : experimental Portability : POSIX * traits: * abstractions: * uniform types for identification of input and output streams ('Inp', 'Out') * higher order functions (stream handler functions, '(SysIo.Handle -> IO s)', '(SysIo.Handle -> s -> IO ())') are applied on streams * can not cause error by "invalid characters", as long as the stream handler functions do not cause them * supports the following file system features: * deletion of files * reading and writing streams * supports the following data types: * Octets * example @ import qualified OctetsVertable as Oct import qualified FileSystem as FS main :: IO () main = do o1 <- FS.readFromStream (FS.FileInp ".\\test\\Spec.hs") Oct.getOctets FS.writeToStream (FS.FileOut ".\\test\\Spec-2.hs") Oct.putOctets o1 FS.writeToStream FS.StdOut Oct.putOctets o1 FS.writeToStream FS.StdErr Oct.putOctets o1 @ * copies the file "Spec.hs" in ".\test" to "Spec-2.hs" * sends to octal representation to 'stdout', and 'stderr' * will not cause uncaught exception caused by "invalid characters" -} module FileSystem ( Inp(..), Out(..), removeFileIfExists, readFromStream, writeToStream ) where import qualified System.IO as SysIo import qualified System.IO.Error as Err import qualified Control.Exception as Excp import qualified System.Directory as Dir -- input streams data Inp = StdInp | FileInp String deriving (Eq, Show) -- output streams data Out = NullOut | StdOut | StdErr | FileOut String deriving (Eq, Show) removeFileIfExists :: FilePath -> IO () removeFileIfExists fileName = Dir.removeFile fileName `Excp.catch` handleExists where handleExists :: Err.IOError -> IO () handleExists e | Err.isDoesNotExistError e = return () | otherwise = Excp.throwIO e readFromStream :: Inp -> (SysIo.Handle -> IO s) -> IO s readFromStream StdInp f = f SysIo.stdin readFromStream (FileInp sFileName) f = do hFile <- SysIo.openFile sFileName SysIo.ReadMode x <- f hFile SysIo.hClose hFile return x writeToStream :: Out -> (SysIo.Handle -> s -> IO ()) -> s -> IO () writeToStream NullOut _ _ = return () writeToStream StdOut f x = f SysIo.stdout x writeToStream StdErr f x = f SysIo.stderr x writeToStream (FileOut sFileName) f x = do hFile <- SysIo.openFile sFileName SysIo.WriteMode f hFile x SysIo.hClose hFile
You could leave a comment if you were logged in.
codesnippets/filesystemioandstreams.1618916488.txt.gz · Last modified: (external edit)
