Sunday 29 May 2016

Haskell: hPutStrLn: Write a string to a file

It is similar to hPutStr, but adds a newline character. 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 hPutStrLn
hPutStrLn :: 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

        hPutStrLn fileHandle "First Line"
        hPutStrLn fileHandle "Second Line"
        hPutStrLn fileHandle "Third Line"
        hPutStrLn 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 Line
Second Line
Third Line
Fourth Line


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



Previous                                                 Next                                                 Home

No comments:

Post a Comment