Friday 27 May 2016

Haskell: hClose: Closing files

By using hClose function, you can close a file handle associated with it. If the handle is writable, its buffer is flushed before closing the handle. If hClose fails for any reason, any further operations (apart from hClose) on the handle will still fail as if hdl had been successfully closed.

Prelude System.IO> :t hClose
hClose :: Handle -> IO ()

Why should I close file handle?
Most operating systems have a limited number of file handles available, so if you fail to close any open file handles, you may run out, which isn't easy to recover from. So it is good practice to close the file handle.

Can I close the handle which is already closed ?
You can, but it don’t have any affect.


FileUtil.hs
import System.IO

getFileContents fileHandle = 
    do
     isEofFile <- hIsEOF fileHandle

     if isEofFile
        then return ()
        else
            do
                 info <- hGetLine fileHandle
                 putStrLn info
                 getFileContents fileHandle

main = do
        putStrLn "Enter file name (Including full path) to read"
        fileName <- getLine
        fileHandle <- openFile fileName ReadMode
        getFileContents fileHandle
        hClose fileHandle

Suppose “today.txt” contain simple “Hello” message.
$ ghc FileUtil.hs
[1 of 1] Compiling Main             ( FileUtil.hs, FileUtil.o )
Linking FileUtil ...
$
$ ./FileUtil
Enter file name (Including full path) to read
today.txt
Hello


Previous                                                 Next                                                 Home

No comments:

Post a Comment