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? I am working on Windows, but would optimally like to add cross platform support.

I am not particularly experienced with Rust at the moment, and haven’t been able to find an answer on the web.

EDIT
The cross platform support is unimportant at the moment 🙂

>Solution :

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.

Here’s an example of how you can use rename to move x from a to 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. If the destination path doesn’t exist, the file will be moved to the root of the b directory. If you want to move the file to a subdirectory of b, you can specify the subdirectory in the destination path. For example, to move the file to b/subdir/x, you would use Path::new("b/subdir/x") as the destination path.

If you want to add cross-platform support to your code, you can use the std::path::PathBuf type instead of 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. 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.

Leave a Reply