[英]Moving files from place to place in Rust
假設我有這樣的文件結構
a
|
+-- x
|
+-- y
b
我希望將 x 從 a 移動到 b,在 Rust 中實現此目標的最佳方法是什么? 我正在研究 Windows,但最希望添加跨平台支持。
我目前對 Rust 不是特別有經驗,並且無法在 web 上找到答案。
編輯目前跨平台支持並不重要:)
要移動 Rust 中的文件或目錄,您可以使用 std::fs::rename function。這個 function 將適用於 Windows 和類 Unix 操作系統。
以下是如何使用重命名將 x 從 a 移動到 b 的示例:
use std::fs;
use std::path::Path;
fn main() -> std::io::Result<()> {
// The path to the file we want to move
let file_path = Path::new("a/x");
// The destination path for the file
let destination_path = Path::new("b/x");
// Use rename to move the file
fs::rename(file_path, destination_path)?;
Ok(())
}
此代碼會將位於 a/x 的文件重命名為 b/x。 如果目標路徑不存在,文件將被移動到 b 目錄的根目錄。 如果要將文件移動到b的子目錄,可以在目標路徑中指定子目錄。 例如,要將文件移動到 b/subdir/x,您可以使用 Path::new("b/subdir/x") 作為目標路徑。
如果要為代碼添加跨平台支持,可以使用 std::path::PathBuf 類型而不是 std::path::Path。 PathBuf 是一種可以以與平台無關的方式保存路徑的類型,它有許多用於操作和使用路徑的方法。 你可以像這樣使用它:
use std::fs;
use std::path::PathBuf;
fn main() -> std::io::Result<()> {
// The path to the file we want to move
let mut file_path = PathBuf::from("a/x");
// The destination path for the file
let mut destination_path = PathBuf::from("b/x");
// Use rename to move the file
fs::rename(file_path, destination_path)?;
Ok(())
}
此代碼適用於 Rust 支持的任何操作系統。
使用std::fs::rename()
移動文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.