move a csv file in rust

To move a CSV file in Rust, you need to:

  1. Import the necessary modules:
main.rs
use std::fs;
use std::io;
use std::path::Path;
47 chars
4 lines
  1. Define the source and destination paths of the file (use Path::new() to create a Path object that can be used with fs::rename())
main.rs
let src_path = Path::new("path/to/source_file.csv");
let dst_path = Path::new("path/to/destination_file.csv");
111 chars
3 lines
  1. Move the file using fs::rename() function, wrapped in a match statement to handle any errors:
main.rs
match fs::rename(&src_path, &dst_path) {
    Ok(_) => println!("File moved successfully!"),
    Err(err) => match err.kind() {
        io::ErrorKind::NotFound => println!("File not found!"),
        io::ErrorKind::PermissionDenied => println!("Permission denied!"),
        _ => println!("Error: {:?}", err),
    },
};
319 chars
9 lines

The fs::rename() function returns a Result<(), io::Error> object, where () indicates an empty tuple (no data is returned on success). If an error occurs, it returns an io::Error object, which contains a kind() method that can be used to determine the type of error.

Here's the full code snippet:

main.rs
use std::fs;
use std::io;
use std::path::Path;

fn main() {
    let src_path = Path::new("path/to/source_file.csv");
    let dst_path = Path::new("path/to/destination_file.csv");

    match fs::rename(&src_path, &dst_path) {
        Ok(_) => println!("File moved successfully!"),
        Err(err) => match err.kind() {
            io::ErrorKind::NotFound => println!("File not found!"),
            io::ErrorKind::PermissionDenied => println!("Permission denied!"),
            _ => println!("Error: {:?}", err),
        },
    };
}
533 chars
18 lines

gistlibby LogSnag