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: 334
rosetta-stone
|language-agnostic
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 tostdout
. The nice thing is that it puts the onus on the user to redirect those streams the way they want. So ifstdin
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.
© Stack Overflow or respective owner