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())
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
fantom
File(`input.text`).readAllLines.each |Str s, Int i| { echo("${i+1}> $s") }
ExpandDiskEdit
groovy
int count = 0
file.eachLine { line ->
println "${++count} > $line"
}
ExpandDiskEdit
groovy
file.eachLine { line, count ->
println "${++count} > $line"
}
DiskEdit
haskell
import Data.List

prefixWithNumber str n = show n ++ "> " ++ str

numberStrings (x:xs) n = prefixWithNumber x n : (numberStrings xs (n+1))
numberStrings [] n = []

main = do
str <- readFile "prefix.hs"
putStrLn (intercalate "\n" (numberStrings (lines str) 1))
DiskEdit
haskell
prefix n str = show n ++ "> " ++ str

main = readFile "prefix.hs" >>=
putStr . unlines . zipWith prefix [1..] . lines

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