🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Files

File IO is reading and writing text that is stored in a file. A program names the file with a plain path such as "notes.txt".

writeFile then readFile

The program writes one line to notes.txt. It then reads the file back and prints the text.

main :: IO ()
main = do
  writeFile "notes.txt" "First line\n"
  contents <- readFile "notes.txt"
  putStr contents

appendFile adds a line

writeFile sets the first line, so the start is certain. appendFile then adds a second line after it.

main :: IO ()
main = do
  writeFile "notes.txt" "Alpha\n"
  appendFile "notes.txt" "Beta\n"
  contents <- readFile "notes.txt"
  putStr contents

writeFile replaces the contents

The first text is printed before the file is written again. The second write fully replaces it.

main :: IO ()
main = do
  writeFile "notes.txt" "Draft one\n"
  first <- readFile "notes.txt"
  putStr first
  writeFile "notes.txt" "Draft two\n"
  second <- readFile "notes.txt"
  putStr second

Example

main :: IO ()
main = do
  writeFile "notes.txt" "Plan\n"
  first <- readFile "notes.txt"
  putStr first
  appendFile "notes.txt" "Review\n"
  final <- readFile "notes.txt"
  putStr final

Key points

  • writeFile: an action that writes text to a file and replaces what was there.
  • readFile: an action that gives the whole text of a file as a String.
  • appendFile: an action that adds text to the end of a file.
  • Path: a plain relative name such as "notes.txt" points at a file beside the program.
  • Lazy reading: readFile hands over its text slowly, so print or measure the text before writing that file again.
  • Fresh start: a writeFile at the start of a program makes the file contents certain.

In this example, writeFile stores the line Plan in notes.txt. The read text is printed at once, which settles that read before the file changes. appendFile adds the line Review, and the final read prints both lines.

Note

the text written can hold newline marks, so one write can store several lines.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What does appendFile "notes.txt" "More\n" do?