View Problem

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
DiskEdit
ruby
File.open("Solution103.rb").each_with_index { |line, count|
puts "#{count} > #{line}
}
ExpandDiskEdit
java
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("Solution104.java"));
String line = null;
int lineNumber = 1;
while ((line=br.readLine())!=null) {
System.out.println(lineNumber + "> " + line);
lineNumber++;
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (br!=null) {
try {
br.close();
} catch (Exception e) {
// ok
}
}
}
ExpandDiskEdit
java 1.5 or later
LineNumberReader lnr = null; PrintWriter pw = null; String line;

try
{
lnr = new LineNumberReader(new FileReader("Solution400.java"));
pw = new PrintWriter(System.out);
while ((line = lnr.readLine()) != null) pw.printf("%d> %s\n", lnr.getLineNumber(), line);
}
DiskEdit
perl
open($fh, '<', $path) or die "can't open $path: $!";
$c = 1;
print $c++ . "> $_" for (<$fh>);
close $fh;
ExpandDiskEdit
groovy
int count = 0
file.eachLine { line ->
println "${++count} > $line"
}
ExpandDiskEdit
groovy
file.eachLine { line, count ->
println "${++count} > $line"
}
ExpandDiskEdit
scala
val source = Source.fromFile(new File("Solution468.scala")).getLines
var n = 1 ; while (source.hasNext) { printf("%d> %s", n, source.next) ; n += 1 }
ExpandDiskEdit
scala
val source = Source.fromFile(new File("Solution469.scala")).getLines
for ((line, n) <- source zipWithIndex) { printf("%d> %s", (n + 1), line) }
DiskEdit
python
for no, line in enumerate(open(__file__)):
print "%d> %s" % (no+1, line.rstrip())
ExpandDiskEdit
cpp C++/CLI .NET 2.0
IO::StreamReader^ stream; String^ ln; int i = 0;

try
{
stream = gcnew IO::StreamReader("test.txt");
while ((ln = stream->ReadLine())) Console::WriteLine("{0}> {1}", ++i, ln);
}
ExpandDiskEdit
cpp C++/CLI .NET 2.0
int i = 0;
for each(String^ line in IO::File::ReadAllLines("test.txt")) Console::WriteLine("{0}> {1}", ++i, line);
ExpandDiskEdit
fsharp
let stream = new StreamReader("test.txt")
let mutable i = 1
let mutable line = stream.ReadLine()
while (line <> null) do printfn "%d> %s" i line ; line <- stream.ReadLine() ; i <- i + 1 done
stream.Close()
ExpandDiskEdit
fsharp
let proc_a_line (filename : string) proc =
let stream = new StreamReader(filename)
let rec proc_a_line' count line =
match line with
| null -> stream.Close()
| _ -> proc count line ; proc_a_line' (count + 1) (stream.ReadLine())
proc_a_line' 1 (stream.ReadLine())

// ------

let _ = proc_a_line "test.txt" (fun i line -> printfn "%d> %s" i line)
ExpandDiskEdit
fsharp
let reader(filename : string) = seq {
use sr = new StreamReader(filename)
while not sr.EndOfStream do
let line = sr.ReadLine()
yield line
done
}

// ------

reader("test.txt") |> Seq.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
ExpandDiskEdit
fsharp
File.ReadAllLines("test.txt") |> Array.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
DiskEdit
fsharp .NET 4
// Unlike ReadAllLines, ReadLines (new in .NET 4) only reads the file
// one line at a time, rather than reading the entire file into an array first.

open System.IO
File.ReadLines("test.txt") |> Seq.iteri (fun i line -> printfn "%d> %s" (i + 1) line)
ExpandDiskEdit
erlang
Reader = fun (IODevice) -> io:get_line(IODevice, "") end,
Worker = fun (Line, N) -> io:format("~B> ~s", [N, Line]), N + 1 end,

while_not_eof("Solution609.erl", Reader, Worker, 1).
ExpandDiskEdit
erlang
Reader = fun (Filename) -> {ok, Contents} = file:read_file(Filename), Contents end,
Transformer = fun (Line, N) -> string:concat(string:concat(integer_to_list(N), "> "), Line) end,
Printer = fun (Line) -> io:format("~s~n", [Line]) end,

Lines = string:tokens(binary_to_list(Reader("Solution610.erl")), "\n"),
NewLines = lists:zipwith(Transformer, Lines, lists:seq(1, length(Lines))),
lists:foreach(Printer, NewLines).
ExpandDiskEdit
php
$lines = file('file.txt');
foreach ($lines as $lnum => $line) {
echo $line_num."> ".$line; // you may want to add a <br />\n
}
DiskEdit
php PHP 5.1.0+
<?php
$lines = new SplFileObject('file.txt');
foreach ($lines as $line) {
echo $line;
}
?>

Submit a new solution for ruby, java, perl, groovy ...