Files
readFile and writeFile
A file is an IO action like the console: readFile :: FilePath -> IO String and writeFile :: FilePath -> String -> IO (). The first reads the whole file as a string, the second replaces its content, and neither needs a handle or an explicit close in the simple case.
module Main (main) where
import System.IO
path :: FilePath
path = "/tmp/haskell-lesson-files.txt"
main :: IO ()
main = do
writeFile path "one\ntwo\n"
appendFile path "three\n"
content <- readFile path
print (lines content)
print (length (lines content))
withFile path ReadMode $ \handle -> do
first <- hGetLine handle
putStrLn ("first: " ++ first)
ghc -Wall -O1 -o files files.hs
./files
["one","two","three"]
3
first: one
The program writes one line, appends two more, reads the file back and then opens it again as a handle to read only the first line. Every step is an action in the same do block, and the pure functions lines and length work on the string the way they work on any list.
appendFile
writeFile truncates an existing file, so a log needs appendFile :: FilePath -> String -> IO (). The two are the same operation with a different mode, and the mode is the whole difference between a file that grows and a file that resets.
writeFile "log.txt" "start\n" -- creates or replaces
appendFile "log.txt" "next\n" -- adds at the end
readFile "log.txt" >>= putStr -- start, next
A log written with writeFile inside a loop keeps only the last line, which is a classic first bug in a program that writes files. The lesson on exceptions comes back to the other half: a write can fail, and the failure is an exception rather than an Either.
Handles and withFile
A handle is an open file with a position and a mode. The safe way to use one is withFile path mode action, which opens the handle, runs the action and closes it even if the action throws; the plain openFile and hClose are the manual version for the cases where a bracket does not fit.
withFile path ReadMode $ \h -> do
line <- hGetLine h
putStrLn line
withFile path WriteMode $ \h -> do
hPutStrLn h "a line"
The modes are ReadMode, WriteMode, AppendMode and ReadWriteMode. Reading from a handle with no data left throws isEOFError in a plain hGetLine, so a loop over a file either checks hIsEOF or uses hGetContents. The next lesson uses the second shape for standard input.
Lazy input and closing
readFile is lazy: it returns a string that is read from the file as it is consumed, and the file stays open until the whole string has been demanded. In a short program that is invisible; in a program that reads many files it is a leak of handles, and the fix is readFile followed by forcing the content, or a strict read such as Data.ByteString.readFile.
content <- readFile path
length content `seq` putStrLn "read" -- forces the whole file now
-- or, without laziness, the strict variant of a bytestring package
The rule that follows: a short config file can be read lazily, and a program that walks a directory tree should read each file strictly or use withFile and a loop. The behaviour is a consequence of the same laziness that makes take 5 [1 ..] work, and it is the reason the lesson on laziness comes later with the tools to measure it.
Exercises
- Write a file of three lines and print the number of characters and of lines.
- Append two lines to the same file and read it back with readFile.
- Use withFile to write a file and then to read its first line.
- Explain what happens if writeFile is called twice with different strings.
- Read a file, reverse its lines and write the result to another file.
- Force the content of a lazily read file with seq and say what changes.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is the type of readFile?
Answer
FilePath -> IO StringreadFile takes a path and returns an action that produces the content.
-
What does writeFile do to an existing file?
Answer
Replaces its content
WriteMode truncates; appendFile is the mode that keeps the old content.
-
Which function is the safe way to use a handle?
Answer
withFile, which closes the handle even on an exceptionwithFile brackets the action between open and close, so the handle is always released.
-
What does this program print?
module Main (main) where main :: IO () main = do writeFile "/tmp/l45.txt" "a\nb\n" content <- readFile "/tmp/l45.txt" print (length (lines content))Answer
2
The file has two lines, and length counts them.
-
Why does readFile keep the file open?
Answer
It is lazy and reads the content as it is demanded
The string is produced on demand, so the handle lives until the whole content has been read.
-
What does appendFile do?
Answer
Adds text at the end of the file, keeping what is there
AppendMode opens the file for writing at its end.
-
What happens when hGetLine reads past the end of a file?
Answer
It throws an isEOFError exception
The handle-based read is partial at the end, which is why loops check hIsEOF or use hGetContents.
-
What does this program print?
module Main (main) where main :: IO () main = do writeFile "/tmp/l45b.txt" "one\n" appendFile "/tmp/l45b.txt" "two\n" content <- readFile "/tmp/l45b.txt" print (lines content)Answer
["one","two"]
writeFile writes the first line and appendFile adds the second.
-
Which mode opens a file for reading and writing?
Answer
ReadWriteModeReadWriteMode allows both directions on the same handle.
-
Why is a log written with writeFile in a loop wrong?
Answer
Each write replaces the file, so only the last line survives
writeFile truncates, so the loop overwrites the log at every iteration.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev