anol
anol

Reputation: 9073

Obtaining a canonical file path

In OCaml, how can I obtain a canonical file path, equivalent to Java's File.getCanonicalPath() (that is, a normalized absolute path)?

Module Filename has a dirname function, but it does not normalize file paths such as /etc/../usr into /usr, for instance.

Upvotes: 3

Views: 1799

Answers (2)

JaneStreet Ocaml Core has Filename.realpath.

Also, google for ocaml realpath (see realpath(3) in C; you might code some wrapper for it)

Upvotes: 3

Ashish Agarwal
Ashish Agarwal

Reputation: 3030

Our phat library defines normalized rather precisely. The library is overkill for most use cases, but we wrote it for applications that deal heavily with the file system. We'll release to opam soon, but for now you'll have to do a couple of pins. Here is a full working example:

$ opam pin add solvuu_build https://github.com/solvuu/solvuu_build
$ opam pin add phat https://github.com/solvuu/phat.git
$ utop
# #require "phat.pure";;
# module Phat = Phat_pure.Std;;
# Phat.(abs_dir "/a/../b/./c/d/" |> ok_exn |> normalize |> to_string);;
- : string = "/b/c/d"

Upvotes: 2

Related Questions