-
-
Save erhangundogan/e079cecf4b9ae6653e7856c615664a32 to your computer and use it in GitHub Desktop.
Reads current directory and sub directories based on the depth (default 0. 1..nth)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (executable | |
| (name main) | |
| (preprocess (pps ppx_deriving.show))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type t = | |
| | File of string | |
| | Folder of string * t list | |
| | MaxDepth | |
| | Error of string | |
| [@@deriving show] | |
| let read_dir_recursive directory max_depth = | |
| let count = ref 0 in | |
| let dir_to_list d = Array.to_list @@ Sys.readdir d in | |
| let rec aux acc current_dir depth entries = | |
| let expand_folder item = | |
| if depth = max_depth then [MaxDepth] | |
| else aux [] item (depth + 1) (dir_to_list item) | |
| in | |
| match entries with | |
| | [] -> acc | |
| | h :: t -> | |
| incr count; | |
| let entry = current_dir ^ "/" ^ h in | |
| try | |
| if Sys.is_directory entry | |
| then aux ((Folder (entry, expand_folder entry)) :: acc) current_dir depth t | |
| else aux ((File entry) :: acc) current_dir depth t | |
| with _ -> aux ((Error entry) :: acc) current_dir depth t | |
| in | |
| let result = aux [] directory 0 (dir_to_list directory) in | |
| (result, !count) | |
| let () = | |
| let depth = | |
| if Array.length (Sys.argv) > 1 then int_of_string Sys.argv.(1) | |
| else 0 | |
| in | |
| let (list, count) = read_dir_recursive (Sys.getcwd ()) depth in | |
| List.iter (fun i -> print_endline (show i)) list; | |
| Printf.printf "Total entries: %d\n" count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment