Sunday 29 May 2016

Haskell: hSeek: Change file handle position

Whenever you are reading some data from file (or) writing some data to file, operating system maintains internal pointer which keeps track of the current position. By using the hSeek function you can change the file handle position.

Prelude System.IO> :t hSeek
hSeek :: Handle -> SeekMode -> Integer -> IO ()

Observe the type signature of hSeek function, it takes a handle, seek mode and an integer as arguments and move the handle position.

Seek mode specifies the handle position movement. There are three modes supported by Haskell.

For the statement ‘hSeek handle mode i’.
SeekMode
Description
AbsoluteSeek
Position is specific to file. The position of handle is set to i.
RelativeSeek
Position is relative to file current position. the position of hdl is set to offset i from the current position. If ‘i’ is positive, it moves the handle forward, else backward.
SeekFromEnd
The position of handle is set to offset i from the end of the file.

Following program skip first 50 bytes and print remaining data. 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


FileUtil.hs
import System.IO

getFileContents fileHandle = 
    do
     isEofFile <- hIsEOF fileHandle

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

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

        --Skip first 50 bytes
        hSeek fileHandle AbsoluteSeek 50

        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
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


You may get following errors while working with hSeek.
Error
Description
isIllegalOperationError
If the Handle is not seekable, or does not support the requested seek mode. For example, sockets are not seekable, you can check whether handle is seekable (or) not using the function hIsSeekable.
isPermissionError
If a system resource limit would be exceeded.




Previous                                                 Next                                                 Home

No comments:

Post a Comment