Sunday 29 May 2016

Haskell: hGetLine: Read file line by line

hGetLine takes a handle and reads a line form file (or) given handle. You may get isEOFError, when handle reaches to end of file.

Prelude System.IO> :t hGetLine
hGetLine :: Handle -> IO String

Suppose ‘today.txt’ contains following data.

$ cat today.txt 
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
11, 12, 13, 14, 15, 16, 17, 18, 19, 20
21, 22, 23, 24, 25, 26, 27, 28, 29, 30
31, 32, 33, 34, 35, 36, 37, 38, 39 40

Following program takes a file name as input and print the information of file line by line.


FileUtil.hs
import System.IO

readDataFrom fileHandle = 
    do 
        isFileEnd <- hIsEOF fileHandle
        if isFileEnd 
            then
                return ("")
            else
                do
                    info <- hGetLine  fileHandle
                    putStrLn info
                    readDataFrom fileHandle


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

        readDataFrom fileHandle

$ runghc FileUtil.hs
Enter file name (Including full path) to read
today.txt
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
11, 12, 13, 14, 15, 16, 17, 18, 19, 20
21, 22, 23, 24, 25, 26, 27, 28, 29, 30
31, 32, 33, 34, 35, 36, 37, 38, 39 40



Previous                                                 Next                                                 Home

No comments:

Post a Comment