Imperative I/O
Even though the Haskell I/O code is purely functional, this does not prevent us from writing imperative style I/O code. Let's start by printing all the lines of the file:
import System.IO import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import Data.Char (chr) main = do h <- openFile "jabberwocky.txt" ReadMode loop h hClose h where loop h' = do isEof <- hIsEOF h' if isEof then putStrLn "DONE..." else do line <- hGetLine h' print $ words line loop h'
Instead of the hGetLine
function, let's use a Data.ByteString.hGet
function to read from the file in chunks of 8 bytes:
chunk <- B.hGet h' 8 print . words $ show chunk –- vs –- line <- hGetLine h' –- print $ words line
The splitting of a chunk into words is not meaningful anymore. We need to accumulate the chunks until we reach...