How do you read a file line by line in your language of choice?

Posted by Jon Ericson on Stack Overflow See other posts from Stack Overflow or by Jon Ericson
Published on 2009-03-24T18:46:05Z Indexed on 2010/05/20 2:20 UTC
Read the original article Hit count: 301

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:

  1. 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.

  2. 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.

© Stack Overflow or respective owner

Related posts about rosetta-stone

Related posts about language-agnostic