Saturday 28 May 2016

Haskell: hTell: Get current position of handle

Haskell System.IO module provides hTell funciton, which takes a handle as argument and return the current position of the handle.

Prelude System.IO> :t hTell
hTell :: Handle -> IO Integer

Suppose today.txt contains following data.
$ cat today.txt 
There are three layers of the human individual: his physiology, 
the body; his psychology, the mind; and his being, his eternal self. 
Love can exist on all the three planes, but its qualities will be different. 
On the plane of physiology, body, it is simply sexuality. 
You can call it love, because the word love seems to be poetic, beautiful. 
But ninety-nine percent of people are calling their sex, love.
Sex is biological, physiological. Your chemistry, your hormones – everything material is involved in it…


Following program read content of today.txt line by line and gives you the position of file handle.

FileUtil.hs
import System.IO

getFileContents fileHandle = 
    do
     isEofFile <- hIsEOF fileHandle

     if isEofFile
        then return ()
        else
            do
                 info <- hGetLine fileHandle
                 putStrLn info

                 handlePosition <- hTell fileHandle
                 putStrLn $ "Handle Position : " ++ (show handlePosition)
                 getFileContents fileHandle

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


$ ghc FileUtil.hs
[1 of 1] Compiling Main             ( FileUtil.hs, FileUtil.o )
Linking FileUtil ...
$ 
$ ./FileUtil
Enter file name (Including full path) to read
today.txt
There are three layers of the human individual: his physiology, 
Handle Position : 65
the body; his psychology, the mind; and his being, his eternal self. 
Handle Position : 135
Love can exist on all the three planes, but its qualities will be different. 
Handle Position : 213
On the plane of physiology, body, it is simply sexuality. 
Handle Position : 272
You can call it love, because the word love seems to be poetic, beautiful. 
Handle Position : 348
But ninety-nine percent of people are calling their sex, love.
Handle Position : 411
Sex is biological, physiological. Your chemistry, your hormones – everything material is involved in it… 
Handle Position : 521


Previous                                                 Next                                                 Home

No comments:

Post a Comment