使用標準函式庫的基本檔案與目錄操作
任務
檔案系統 / 基本檔案與目錄操作
存在性檢查、複製、移動(重新命名)、刪除、變更目錄、列出目錄、刪除目錄。
不使用任何套件
此食譜僅使用 OCaml 標準函式庫。程式碼
透過測試檔名檢查檔案或目錄是否存在。
let file_exists filename =
if Sys.file_exists filename then
Printf.printf "The file/directory '%s' exists.\n"
filename
else
Printf.printf "The file/directory '%s' does not \
exist.\n" filename
檢查給定的路徑是目錄還是檔案。
let check_if_directory path =
if Sys.file_exists path then
(if Sys.is_directory path then
Printf.printf "'%s' is a directory.\n" path
else
Printf.printf "'%s' is a file.\n" path)
else
Printf.printf "'%s' does not exist.\n" path
將來源檔案的內容複製到目標檔案。
let copy_file src dst =
let content =
In_channel.with_open_text src In_channel.input_all
in
Out_channel.with_open_text dst (fun out_channel ->
Out_channel.output_string out_channel content);
Printf.printf "Copied '%s' to '%s'.\n" src dst
將檔案移動(重新命名)到新的位置或名稱。
let move_file src dst =
if Sys.file_exists src then (
Sys.rename src dst;
Printf.printf "Moved '%s' to '%s'.\n" src dst
) else
Printf.printf "File '%s' does not exist.\n" src
如果指定的檔案存在且不是目錄,則刪除該檔案。
let delete_file filename =
if Sys.file_exists filename &&
not (Sys.is_directory filename) then (
Sys.remove filename;
Printf.printf "Deleted file '%s'.\n" filename
) else
Printf.printf "File '%s' does not exist or is \
a directory.\n" filename
將目前的工作目錄變更為指定的目錄路徑。
let change_directory dir =
if Sys.file_exists dir && Sys.is_directory dir then (
Sys.chdir dir;
Printf.printf "Changed current directory to '%s'.\n"
dir
) else
Printf.printf "'%s' does not exist or is not \
a directory.\n" dir
如果指定的目錄存在,則刪除該目錄。
let delete_directory dir =
if Sys.file_exists dir && Sys.is_directory dir then (
Sys.rmdir dir;
Printf.printf "Deleted directory '%s'.\n" dir
) else
Printf.printf "'%s' does not exist or is not \
a directory.\n" dir
列出指定目錄內的所有檔案和目錄。如果路徑不存在或不是目錄,則列印內容名稱,否則列印錯誤訊息。
let list_directory dir =
if Sys.file_exists dir && Sys.is_directory dir then (
let file_array = Sys.readdir dir in
Printf.printf "Contents of directory '%s':\n" dir;
Array.iter (fun filename ->
Printf.printf " %s\n" filename) file_array
) else
Printf.printf "'%s' does not exist or is not \
a directory.\n" dir
討論
- 所有呈現的函式都可以在 Sys 模組參考 中找到。