Sunday, 29 May 2016

Haskell: hPutStr: Write a string to a file

System.IO module provides hPutStr function to write a string to a file. You may get following errors, while working with hPutStr.

a.   isFullError if the device is full.
b.   isPermissionError if another system resource limit would be exceeded.

Prelude System.IO> :t hPutStr
hPutStr :: Handle -> String -> IO ()

FileUtil.hs
import System.IO

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

        hPutStr fileHandle "First Line"
        hPutStr fileHandle "Second Line"
        hPutStr fileHandle "Third Line"
        hPutStr fileHandle "Fourth Line"

        hClose fileHandle

$ cat abc.txt
Hello Hari
How are you
where are you now
$ 
$ runghc FileUtil.hs
Enter file name (Including full path) to read
abc.txt
$ 
$ 
$ cat abc.txt
First LineSecond LineThird LineFourth Line


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



Previous                                                 Next                                                 Home

No comments:

Post a Comment