Files
The simplest way to read a file in Haskell is the readFile function. We pass it the name of the file as a String, and it slurps up all the text and returns an IO String, which we unbox using the <- command:
main = do
text <- readFile "playlist.txt"
putStrLn text
main = do text <- readFile "playlist.txt" putStrLn text
If we want to process the file line by line, we use the lines function, which splits up a String on its linebreaks. It is a pure function, not an IO function, which means we assign its result to a variable using =. Here it is used in a let binding:
main = do
text <- readFile "playlist.txt"
let entries = lines text
putStrLn (show entries)
main = do text <- readFile "playlist.txt" let entries = lines text putStrLn (show entries)
There's also a similar words function that breaks the text up on any whitespace, not just linebreaks.
The counterpart to readFile is writeFile. We pass it the name of a file and the String to write:
main = do
writeFile "baby-names.txt" "Slar\nBizness\nRuckus\n"
main = do writeFile "baby-names.txt" "Slar\nBizness\nRuckus\n"
If we don't want to assemble a single String that we output all at once, we use openFile from the System.IO module. It returns a file handle, which we pass to the accompanying hPutStrLn to output one line at a time:
import System.IO
main = do
file <- openFile "baby-names.xt" WriteMode
hPutStrLn file "Slar"
hPutStrLn file "Bizness"
hPutStrLn file "Ruckus"
hClose file
import System.IO main = do file <- openFile "baby-names.xt" WriteMode hPutStrLn file "Slar" hPutStrLn file "Bizness" hPutStrLn file "Ruckus" hClose file