O'Reilly logo

Real World Haskell by Donald Bruce Stewart, Bryan O'Sullivan, John Goerzen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Working with Files and Handles

So far, you’ve seen how to interact with the user at the computer’s terminal. Of course, you’ll often need to manipulate specific files. That’s easy to do, too.

Haskell defines quite a few basic functions for I/O, many of which are similar to functions seen in other programming languages. The library reference for System.IO provides a good summary of all the basic I/O functions, should you need one that we aren’t touching upon here.

You will generally begin by using openFile, which will give you a file Handle. That Handle is then used to perform specific operations on the file. Haskell provides functions such as hPutStrLn that work just like putStrLn but take an additional argument, a Handle, that specifies which file to operate upon. When you’re done, you’ll use hClose to close the Handle. These functions are all defined in System.IO, so you’ll need to import that module when working with files. There are “h” functions corresponding to virtually all of the non-“h” functions; for instance, there is print for printing to the screen and hPrint for printing to a file.

Let’s start with an imperative way to read and write files. This should seem similar to a while loop that you may find in other languages. This isn’t the best way to write it in Haskell; later, you’ll see examples of more Haskellish approaches.

-- file: ch07/toupper-imp.hs import System.IO import Data.Char(toUpper) main :: IO () main = do inh <- openFile "input.txt" ReadMode outh <- openFile ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required