Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 57 ยท IO and the real world

Files, Arguments and Environment

Read and write files in Haskell with readFile, writeFile and withFile, handle getArgs and exit codes, and avoid the lazy IO trap.

Real programs read files, take command-line arguments, look at environment variables and report success or failure through an exit code. Haskell does all of this with ordinary IO actions, mostly from base: System.IO, System.Environment and System.Exit. This lesson covers the common ones, plus the best-known gotcha: lazy IO.

The real functions are read-only on this site, because there is no Haskell runtime here and the browser has no file system. The runnable blocks use JavaScript stand-ins with an in-memory "disk" and a list of arguments, so you can practise the structure.

Whole-file helpers

The Prelude includes the simplest file functions:

HASKELL
readFile   :: FilePath -> IO String
writeFile  :: FilePath -> String -> IO ()
appendFile :: FilePath -> String -> IO ()

FilePath is just a type synonym for String.

HASKELL
main :: IO ()
main = do
  writeFile "notes.txt" "first line\n"
  appendFile "notes.txt" "second line\n"
  contents <- readFile "notes.txt"
  putStr contents
  putStrLn ("lines: " ++ show (length (lines contents)))

writeFile replaces the file (creating it if needed), while appendFile adds to the end. If a file does not exist, readFile throws an IOException; see Exceptions and Error Handling for how to catch it.

Handles and withFile

For more control you work with a Handle. withFile opens a file, runs your function and always closes the file afterwards, even when an error occurs:

HASKELL
import System.IO

main :: IO ()
main = do
  withFile "log.txt" WriteMode $ \h -> do
    hPutStrLn h "starting"
    hPutStrLn h "done"
  withFile "log.txt" ReadMode $ \h -> do
    first <- hGetLine h
    putStrLn ("first: " ++ first)

The modes are ReadMode, WriteMode, AppendMode and ReadWriteMode. Functions that take a handle start with h: hPutStrLn, hGetLine, hClose, hIsEOF. Three handles are always open: stdin, stdout and stderr. Print diagnostics to stderr so they do not mix with normal output:

HASKELL
hPutStrLn stderr "warning: config file missing, using defaults"

Three ways to read a file

readFile Simple, but lazy.
withFile Opens, runs, always closes.
Text.IO Strict reading in one step.

For big or important files, prefer the strict versions.

1 / 2

The lazy IO caveat

readFile and getContents are lazy: they return immediately and read the file in chunks as you consume the string. That is neat for streaming, but it surprises people in three ways:

  1. Files stay open. The handle is only closed after the whole string has been read. Open thousands of files without consuming them and you run out of file descriptors.
  2. You cannot overwrite what you are still reading. This classic program fails with an error such as "resource busy (file is locked)":
HASKELL
main = do
  s <- readFile "data.txt"
  writeFile "data.txt" (map toUpper s)  -- data.txt is still being read
  1. withFile plus lazy reading gives empty or truncated results. The handle is closed before the string is consumed:
HASKELL
broken :: IO String
broken = withFile "data.txt" ReadMode hGetContents   -- lazy: handle closed too early

The fixes are to force the whole content while the file is open, or to use a strict function. Modern base has readFile' and hGetContents' in System.IO, both strict. The text and bytestring packages offer Data.Text.IO.readFile and Data.ByteString.readFile, which also read everything at once:

HASKELL
import System.IO

fixed :: IO String
fixed = withFile "data.txt" ReadMode hGetContents'

simple :: IO String
simple = readFile' "data.txt"

Use lazy reading on purpose for streaming through large files with interact-style code; otherwise reach for the strict forms.

JS An in-memory disk (a stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Command-line arguments

System.Environment gives you the arguments (not including the program name):

HASKELL
import System.Environment (getArgs, getProgName)
import System.IO (readFile')

main :: IO ()
main = do
  args <- getArgs
  name <- getProgName
  putStrLn (name ++ " got " ++ show (length args) ++ " arguments")
  case args of
    [path]       -> readFile' path >>= putStr
    [path, "-n"] -> readFile' path >>= putStr . unlines . zipWith numbered [1 ..] . lines
    _            -> putStrLn "usage: tool FILE [-n]"
  where
    numbered i l = show i ++ ": " ++ l

Pattern matching on the list of strings is a quick way to build a small interface, using the same pattern matching skills as anywhere else. For real tools with flags and help text, the optparse-applicative library is the usual choice; the todo-app project later in this course uses it.

Run a compiled program with ./tool notes.txt -n, or try it quickly with runghc tool.hs notes.txt -n. To pass flags to a program through Cabal, write cabal run tool -- notes.txt -n.

Environment variables

lookupEnv :: String -> IO (Maybe String) returns Nothing when a variable is unset, so it composes with Maybe helpers:

HASKELL
import Data.Maybe (fromMaybe)
import System.Environment (lookupEnv)

main :: IO ()
main = do
  home <- lookupEnv "HOME"
  port <- fromMaybe "8080" <$> lookupEnv "PORT"
  putStrLn ("home: " ++ show home)
  putStrLn ("port: " ++ port)

getEnv throws if the variable is missing, and getEnvironment returns every pair as a list. Prefer lookupEnv: a missing variable is normal, not exceptional.

Exit codes

When main finishes normally, the program exits with code 0. To signal failure, use System.Exit:

HASKELL
import System.Environment (getArgs)
import System.Exit
import System.IO

main :: IO ()
main = do
  args <- getArgs
  case args of
    [] -> do
      hPutStrLn stderr "error: no input file"
      exitWith (ExitFailure 2)
    _  -> putStrLn "ok" >> exitSuccess

exitFailure is shorthand for exitWith (ExitFailure 1). Under the hood, exitWith throws an ExitCode exception, which is why it unwinds bracket and finally handlers properly but can be accidentally caught by a too-broad catch.

A tidy design keeps the decision pure: a function from arguments and input to an output and an exit code, and a tiny main that performs it.

JS Arguments and exit codes: pure core

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does appendFile do if the file already exists?

    appendFile adds to the end (creating the file if needed), while writeFile replaces the contents.
  2. 2. Why can withFile path ReadMode hGetContents return an empty or truncated string?

    Lazy reading delays the actual read. Use the strict hGetContents' (or readFile') so the content is read while the file is open.
  3. 3. What does getArgs return for ./tool a.txt -n?

    getArgs :: IO [String] excludes the program name, which comes from getProgName.
  4. 4. Which call makes a program exit with code 3?

    ExitFailure n carries the exit code; exitFailure always uses 1.

Summary

  • readFile, writeFile and appendFile cover whole-file work; withFile gives a handle and always closes it.
  • readFile and hGetContents are lazy; use readFile', hGetContents' or Text/ByteString functions to read strictly.
  • getArgs, getProgName and lookupEnv come from System.Environment; lookupEnv returns a Maybe.
  • exitWith (ExitFailure n) sets the exit code; send error messages to stderr.
  • Keep decisions in pure functions and let main perform the effects.

Next, we handle things that go wrong: Exceptions and Error Handling.