Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.

import System.IO

main =
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
$ cat abc.txt
"Hari Krishna"

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

This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Haskell: hPrint: Write data to file


Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription