假设我想在foo
使用其参数调用它之前检查某个可执行文件是否有效.可以从命令行获得各种这样的方法(例如,$> hash foo
).
但是,据我所知,OCaml Sys
和Unix
模块都没有提供内置的功能.
如何定义一个接受指示unix可执行文件的字符串的机制,并返回一个指示参数是否可执行的bool?
允许您检查文件是否可执行的功能是Unix.access
.如果您想要另外搜索路径,则需要额外的脚手架,例如:
let syspath = String.split_on_char ':' (Sys.getenv "PATH") let check_executable path = let open Unix in try access path [ X_OK ]; Some path with _ -> None let starts_with s prefix = let open String in let plen = length prefix in length s >= plen && sub s 0 plen = prefix let search_path name = if starts_with name "/" || starts_with name "./" || starts_with name "../" then check_executable name else List.fold_left (fun acc dir -> match acc with | Some file -> Some file | None -> check_executable (Filename.concat dir name) ) None syspath let main () = Array.iter (fun arg -> match search_path arg with | None -> Printf.printf "%s (Not found)\n" arg | Some file -> Printf.printf "%s -> %s\n" arg file) Array.(sub Sys.argv 1 (length Sys.argv - 1)) let () = main ()