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
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 is then used to perform specific
operations on the file. Haskell provides functions such as
work just like
putStrLn but take
an additional argument, a
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,
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 ...