hGetContents function takes a handle as
argument and returns the list of characters corresponding to the unread portion
of the channel or file managed by the handle. When you call hGetContents on a
handle, it puts the handle into semi-closed state.
Any operation that fails when handle
closed is also fail when handle is in semi closed state.
When semi-closed handle becomes closed?
a. When you call hClose on semi-closed handle
b. If you got I/O error while reading data
from semi closed handle
c. When all the contents of semi closed handle
are read.
What
happens when I close a semi-closed handle?
The result contains at least all the
items of the stream that were evaluated prior to the handle becoming closed.
Suppose today.txt contains following
data.
$ cat today.txt 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 31, 32, 33, 34, 35, 36, 37, 38, 39 40
FileUtil.hs
FileUtil.hs import System.IO main = do putStrLn "Enter file name (Including full path) to read" fileName <- getLine fileHandle <- openFile fileName ReadMode contents <- hGetContents fileHandle isHandleClosed <- hIsClosed fileHandle putStrLn $ "Is Handle closed " ++ show isHandleClosed putStrLn contents isHandleClosed <- hIsClosed fileHandle putStrLn $ "Is Handle closed " ++ show isHandleClosed
$ runghc FileUtil.hs Enter file name (Including full path) to read today.txt Is Handle closed False 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 31, 32, 33, 34, 35, 36, 37, 38, 39 40 Is Handle closed True
No comments:
Post a Comment