Haskell File Handles
A Haskell file handle is an open connection to a file. It lets a program read or write one piece at a time and then close the connection.
hGetLine reads one line at a time
The file holds two lines. Each hGetLine call reads the next line.
import System.IO
main :: IO ()
main = do
writeFile "handles-a.txt" "one\ntwo\n"
h <- openFile "handles-a.txt" ReadMode
a <- hGetLine h
b <- hGetLine h
hClose h
print [a,b]hPutStrLn writes through a handle
A write handle stores two lines. Closing it makes the text safe to read back.
import System.IO
main :: IO ()
main = do
h <- openFile "handles-b.txt" WriteMode
hPutStrLn h "red"
hPutStrLn h "blue"
hClose h
txt <- readFile "handles-b.txt"
putStr txthIsEOF reports the end of a file
The file holds a single line. After that line is read, the handle is at the end.
import System.IO
main :: IO ()
main = do
writeFile "handles-c.txt" "only\n"
h <- openFile "handles-c.txt" ReadMode
line <- hGetLine h
eof <- hIsEOF h
hClose h
print (line, eof)Example
import System.IO
main :: IO ()
main = do
writeFile "handles-src.txt" "alpha\nbeta\n"
src <- openFile "handles-src.txt" ReadMode
dst <- openFile "handles-dst.txt" WriteMode
a <- hGetLine src
b <- hGetLine src
hPutStrLn dst a
hPutStrLn dst b
hClose dst
hClose src
txt <- readFile "handles-dst.txt"
putStr txtKey points
- Handle: a handle is the open connection a program uses to read from or write to a file.
- Open: openFile opens a file in a read mode or a write mode.
- Get line: hGetLine reads one line from a read handle.
- Put line: hPutStrLn writes one line to a write handle.
- Close: hClose closes a handle and flushes any buffered output.
In this example, the program writes two lines to a source file. It opens the source for reading and a second file for writing. It copies each line across, closes both handles, and reads the second file back.
Note
a write handle must be closed before the same file is read back.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
Why must a program close a write handle before reading the file back?