Thanks a lot tilly and Bloodnok. Both solutions are quite elegant.
In my problem, I find it convenient to have an output.txt file for later viewing. Also, I need the user to mention the names of input and output files.
So I would use Bloodnok's solution for my problem.