File IO

Reading a Whole File

file: rdf.hs
1 main = do
2     line <- readFile "/etc/group"
3     putStrLn line
 

Reading a File Line by Line

file: rdf2.hs
1 import System.IO
2 
3 doline fh = do
4     line <- hGetLine fh
5     putStrLn line
6     prlines fh
7 
8 prlines fh = do
9     eof <- hIsEOF fh
10     case eof of
11         True -> putStr ""
12         False -> doline fh
13 
14 main = do
15     fh <- openFile "/etc/group" ReadMode
16     prlines fh
17     hClose fh
 

See http://cgi.cse.unsw.edu.au/~dons/blog/2006/12/17.

The problem with this approach is that it betrays an imperative way of thinking. Possibly the programmer was worried that readFile, because it returns the entire contents of a file as a string, was wasting memory. Not so. Haskell is smart enough to only read as much of the file as it needs to.


Read a File Line by Line, Again

file: rdfs3.hs
1 -- Split up a string into an array, using character c as a delimiter
2 split _ [] = []
3 split c str =
4     (takeWhile (c /= ) str) : (split c (drop 1 (dropWhile (c /=) str)))
5 
6 -- Print out lines one by one
7 prlines [] = putStr ""
8 prlines (a:b) = do
9     putStrLn a
10     prlines b
11 
12 main = do
13     file <- readFile "/etc/group"
14     prlines(split '\n' file)