Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading