Sunday 29 May 2016

Haskell: hPutChar: Write character to a file

System.IO module provides hPutChar function to write single character to a file. You may get following errors while working with hPutChar.

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

Prelude System.IO> :t hPutChar
hPutChar :: Handle -> Char -> IO ()


FileUtil.hs
import System.IO

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

        hPutChar fileHandle 'H'
        hPutChar fileHandle 'e'
        hPutChar fileHandle 'l'
        hPutChar fileHandle 'l'
        hPutChar fileHandle 'o'
        hPutChar fileHandle ' '
        hPutChar fileHandle 'P'
        hPutChar fileHandle 'T'
        hPutChar fileHandle 'R'

        hClose fileHandle

$ runghc FileUtil.hs
Enter file name (Including full path) to read
abc.txt
$ 
$ cat abc.txt
Hello PTR



Previous                                                 Next                                                 Home

No comments:

Post a Comment