How do you read a file line by line in your language of choice?
- by Jon Ericson
I got inspired to try out Haskell again based on a recent answer. My big block is that reading a file line by line (a task made simple in languages such as Perl) seems complicated in a functional language. How do you read a file line by line in your favorite language?
So that we are comparing apples to other types of apples, please write a program that numbers the lines of the input file. So if your input is:
Line the first.
Next line.
End of communication.
The output would look like:
1 Line the first.
2 Next line.
3 End of communication.
I will post my Haskell program as an example.
Ken commented that this question does not specify how errors should be handled. I'm not overly concerned about it because:
Most answers did the obvious thing and read from stdin and wrote to stdout. The nice thing is that it puts the onus on the user to redirect those streams the way they want. So if stdin is redirected from a non-existent file, the shell will take care of reporting the error, for instance.
The question is more aimed at how a language does IO than how it handles exceptions.
But if necessary error handling is missing in an answer, feel free to either edit the code to fix it or make a note in the comments.