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
python 2.6
for no, line in enumerate(open(__file__)):
print "{0}> {1}".format(no+1, line.rstrip())
DiskEdit
csharp .Net 2.0 or later
int counter = 0;

// If the file is large, you would want to buffer this instead of reading everything at once
foreach (string line in System.IO.File.ReadAllLines("filename.txt"))
{
Console.WriteLine("{0}> {1}", ++counter, 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);
}
ExpandDiskEdit
fantom
File(`input.text`).readAllLines.each |Str s, Int i| { echo("${i+1}> $s") }

Submit a new solution for python, csharp, java, or fantom
There are 23 other solutions in additional languages (clojure, cpp, erlang, fsharp ...)