Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a file line by line

Tags:

haskell

I'm trying to read a file line by line, but I don't know how to stop when I reach the EOF.

I have this code:

readWholeFile = do inputFile <- openFile "example.txt" ReadMode
                readALine inputFile

readALine x = do y <- hGetLine x
                 print y
                 readALine x

and it obviously always terminata raising an exception.

How can I solve?

Edit: exact error message is:

*** Exception: example.txt: hGetLine: end of file
like image 519
Aslan986 Avatar asked Sep 05 '12 19:09

Aslan986


4 Answers

One more solution. You can lazy read file with readFile, lazy split it on-demand and take result line by line:

readLines :: FilePath -> IO [String]
readLines = fmap lines . readFile
like image 82
Fedor Gogolev Avatar answered Oct 20 '22 07:10

Fedor Gogolev


What you are looking for is, hIsEOF

Check out http://book.realworldhaskell.org/read/io.html

like image 30
verheesj Avatar answered Oct 20 '22 08:10

verheesj


You can use hIsEOF to check the EOF status manually before reading a line, or you can just use the readily available (lazy) readFile function.

like image 8
Niklas B. Avatar answered Oct 20 '22 07:10

Niklas B.


You can test the handle x with hIsEOF before reading further. hGetLine fails when the end of file is encountered when reading the first character of the line

like image 4
Phyx Avatar answered Oct 20 '22 07:10

Phyx