[project @ 2000-04-11 11:06:34 by simonmar]
[ghc-hetmet.git] / ghc / tests / io / should_run / io030.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 "io030.hs" ReadMode
18   sequence (zipWith testPosns (repeat hdl) bmo_ls)
19   hClose hdl
20
21 testPositioning hdl = do
22   hSeek hdl AbsoluteSeek 0  -- go to the beginning of the file again.
23   ps   <- getFilePosns 10 hdl
24   hSeek hdl AbsoluteSeek 0
25   putStr "First ten chars: "
26   ls   <- hGetChars 10 hdl
27   putStrLn ls
28     -- go to the end
29   hSeek hdl SeekFromEnd 0  
30   ls   <- sequence (map (\ p -> hSetPosn p >> hGetChar hdl) ps)
31   putStr "First ten chars: "
32   putStrLn ls
33
34     -- position ourselves in the middle.
35   sz <- hFileSize hdl
36   hSeek hdl AbsoluteSeek (sz `div` 2)
37   ls   <- sequence (map (\ p -> hSetPosn p >> hGetChar hdl) ps)
38   putStr "First ten chars: "
39   putStrLn ls
40
41 hGetChars :: Int -> Handle -> IO String
42 hGetChars n h = sequence (replicate n (hGetChar h))
43
44 getFilePosns :: Int -> Handle -> IO [HandlePosn]
45 getFilePosns 0 h = return []
46 getFilePosns x h = do
47    p <- hGetPosn h
48    hGetChar h
49    ps <- getFilePosns (x-1) h
50    return (p:ps)