简体   繁体   English

在 Rust 中将文件从一个地方移动到另一个地方

[英]Moving files from place to place in Rust

Say I have a file structure like so假设我有这样的文件结构

a
|
+-- x
|
+-- y
b

and I wish to move x from a to b, what would be the best way of achieving this in Rust?我希望将 x 从 a 移动到 b,在 Rust 中实现此目标的最佳方法是什么? I am working on Windows, but would optimally like to add cross platform support.我正在研究 Windows,但最希望添加跨平台支持。

I am not particularly experienced with Rust at the moment, and haven't been able to find an answer on the web.我目前对 Rust 不是特别有经验,并且无法在 web 上找到答案。

EDIT The cross platform support is unimportant at the moment:)编辑目前跨平台支持并不重要:)

To move a file or directory in Rust, you can use the std::fs::rename function. This function will work on both Windows and Unix-like operating systems.要移动 Rust 中的文件或目录,您可以使用 std::fs::rename function。这个 function 将适用于 Windows 和类 Unix 操作系统。

Here's an example of how you can use rename to move x from a to b:以下是如何使用重命名将 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(())
}

This code will rename the file at a/x to b/x.此代码会将位于 a/x 的文件重命名为 b/x。 If the destination path doesn't exist, the file will be moved to the root of the b directory.如果目标路径不存在,文件将被移动到 b 目录的根目录。 If you want to move the file to a subdirectory of b, you can specify the subdirectory in the destination path.如果要将文件移动到b的子目录,可以在目标路径中指定子目录。 For example, to move the file to b/subdir/x, you would use Path::new("b/subdir/x") as the destination path.例如,要将文件移动到 b/subdir/x,您可以使用 Path::new("b/subdir/x") 作为目标路径。

If you want to add cross-platform support to your code, you can use the std::path::PathBuf type instead of std::path::Path.如果要为代码添加跨平台支持,可以使用 std::path::PathBuf 类型而不是 std::path::Path。 PathBuf is a type that can hold a path in a platform-agnostic way, and it has a number of methods for manipulating and working with paths. PathBuf 是一种可以以与平台无关的方式保存路径的类型,它有许多用于操作和使用路径的方法。 You can use it like this:你可以像这样使用它:

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(())
}

This code will work on any operating system that Rust supports.此代码适用于 Rust 支持的任何操作系统。

Use std::fs::rename() to move a file.使用std::fs::rename()移动文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM