Monday 30 May 2016

Haskell: hPrint: Write data to file

Prelude System.IO> :t hPrint
hPrint :: Show a => Handle -> a -> IO ()

Observe the signature of hPrint, it takes a Handle, variable ‘a’, which derives Show class and write it to the file.


FileUtil.hs
import System.IO

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

        hPrint fileHandle "Hari Krishna"
        hPrint fileHandle "Gurram"
        hPrint fileHandle 523169
        hPrint fileHandle 12345.6

        hClose fileHandle

$ cat abc.txt
First Line
Second Line
Third Line
Fourth Line
$ 
$ runghc FileUtil.hs
Enter file name (Including full path) to read
abc.txt
$ 
$ cat abc.txt 
"Hari Krishna"
"Gurram"
523169
12345.6


Observe the output, hPrint overrides the existing data in the file abc.txt.

Difference between hPrint, hPutStrLn
hPrint function displays value of any printable type to the standard output device. hPrint function do this by calling show on its input first.

Technically hPrint is defined like below.

hPrint x = hPutStrLn (show x)




Previous                                                 Next                                                 Home

No comments:

Post a Comment