[project @ 2001-06-01 13:07:35 by sewardj]
[ghc-hetmet.git] / ghc / tests / lib / IO / hSeek003.hs
1 -- !!! file positions (hGetPosn and hSetPosn)
2 module Main(main) where
3
4 import IO
5 import Monad ( sequence )
6
7 testPosns :: Handle -> BufferMode -> IO ()
8 testPosns hdl bmo = do
9    hSetBuffering hdl bmo
10    putStrLn ("Testing positioning with buffer mode set to: " ++ show bmo)
11    testPositioning hdl
12
13 bmo_ls = [NoBuffering, LineBuffering, BlockBuffering Nothing, 
14           BlockBuffering (Just 511),BlockBuffering (Just 3), BlockBuffering (Just 11)]
15
16 main = do
17   hdl  <- openFile "hSeek003.hs" ReadMode
18   hSetBinaryMode hdl True
19   sequence (zipWith testPosns (repeat hdl) bmo_ls)
20   hClose hdl
21
22 testPositioning hdl = do
23   hSeek hdl AbsoluteSeek 0  -- go to the beginning of the file again.
24   ps   <- getFilePosns 10 hdl
25   hSeek hdl AbsoluteSeek 0
26   putStr "First ten chars: "
27   ls   <- hGetChars 10 hdl
28   putStrLn ls
29     -- go to the end
30   hSeek hdl SeekFromEnd 0  
31   ls   <- sequence (map (\ p -> hSetPosn p >> hGetChar hdl) ps)
32   putStr "First ten chars: "
33   putStrLn ls
34
35     -- position ourselves in the middle.
36   sz <- hFileSize hdl
37   hSeek hdl AbsoluteSeek (sz `div` 2)
38   ls   <- sequence (map (\ p -> hSetPosn p >> hGetChar hdl) ps)
39   putStr "First ten chars: "
40   putStrLn ls
41
42 hGetChars :: Int -> Handle -> IO String
43 hGetChars n h = sequence (replicate n (hGetChar h))
44
45 getFilePosns :: Int -> Handle -> IO [HandlePosn]
46 getFilePosns 0 h = return []
47 getFilePosns x h = do
48    p <- hGetPosn h
49    hGetChar h
50    ps <- getFilePosns (x-1) h
51    return (p:ps)