Snippets

Cameron Presley Create a report with line count for every file in a directory

Created by Cameron Presley last modified
open System.IO
open System

let getFiles directory = 
    match Directory.Exists directory with
    | true -> Directory.GetFiles(directory) |> Option.Some
    | false -> None

let countLines (file:string) = 
    use reader = new StreamReader(file)
    let content = reader.ReadToEnd()
    content.ToCharArray() |> Array.fold (fun state item -> if item='\n' then state + 1 else state + 0) 0

let printReport directory =
    match directory |> getFiles with
        | None -> printfn "Couldn't get any files from the directory."
        | Some files -> 
            let lineCounts = files |> Array.map (fun x -> countLines x)
            Array.iter2 (fun x y -> printfn "File: %s - %i lines" x y) files lineCounts
            
// Example usage
printfn "Enter a directory"
Console.ReadLine() |> printReport

Comments (2)

  1. chosen breed

    I like it! I've not dealt much with the Array module but this looks good. There are probably a number of ways to count lines. This seems as good as any. You gotta' love the "use" construct. I ran it in F# Interactive and works a treat :-)

    1. Cameron Presley

      Totally! The fact that use takes care of disposing is awesome. Thanks for the feedback.

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.