Sunday 29 May 2016

Haskell: hLookAhead: Return next character from file

hLookAhead funciton takes a file handle returns the next character from the handle.  It will not remove the charcater from input buffer, so you will always get the same character until it removed from the buffer.

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

Prelude System.IO> :t hLookAhead
hLookAhead :: Handle -> IO Char

Following program end up in infinite loop, since the hLookAhead function read a character and doesn’t remove it from buffer.


FileUtil.hs
import System.IO

readDataFrom fileHandle = 
    do 
        isFileEnd <- hIsEOF fileHandle
        if isFileEnd 
            then
                return ("")
            else
                do
                    info <- hLookAhead fileHandle
                    -- hGetChar fileHandle -- If you don't uncomment this you will end up in infinite loop
                    putStr (show info)
                    readDataFrom fileHandle

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

        readDataFrom fileHandle

To make it work proper uncomment the line ‘-- hGetChar fileHandle’ and rerun.

FileUtil.hs
import System.IO

readDataFrom fileHandle = 
    do 
        isFileEnd <- hIsEOF fileHandle
        if isFileEnd 
            then
                return ("")
            else
                do
                    info <- hLookAhead fileHandle
                    hGetChar fileHandle -- If you don't uncomment this you will end up in infinite loop
                    putStr (show 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'','' ''1''0''\n''1''1'','' ''1''2'','' ''1''3'','' ''1''4'','' ''1''5'','' ''1''6'','' ''1''7'','' ''1''8'','' ''1''9'','' ''2''0''\n''2''1'','' ''2''2'','' ''2''3'','' ''2''4'','' ''2''5'','' ''2''6'','' ''2''7'','' ''2''8'','' ''2''9'','' ''3''0''\n''3''1'','' ''3''2'','' ''3''3'','' ''3''4'','' ''3''5'','' ''3''6'','' ''3''7'','' ''3''8'','' ''3''9'' ''4''0''\n'




Previous                                                 Next                                                 Home

No comments:

Post a Comment