如何在Rust中删除文件夹或文件?

zf2sa74q  于 2023-11-19  发布在  其他
关注(0)|答案(1)|浏览(210)

我正在做一个文件夹镜像,当我删除一个文件或文件夹,我得到以下错误:

  1. Running `target/debug/back-rust -b /home/michael/Downloads -s /home/michael/Documents/Michael/`
  2. Watching /home/michael/Documents/Michael for changes
  3. thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:115:53
  4. note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

字符串
当我试图删除一个文件夹
这是我的代码:utils/remove_file.rs:

  1. use std::fs;
  2. use std::path::{Path, PathBuf};
  3. pub fn remove_file(source_base_path: PathBuf, from_path: PathBuf, to_directory: PathBuf) {
  4. let relative_path = from_path.strip_prefix(&source_base_path).unwrap();
  5. let destination_path = to_directory.join(relative_path);
  6. if destination_path.is_file() {
  7. fs::remove_file(&destination_path).unwrap();
  8. } else if destination_path.is_dir() {
  9. fs::remove_dir_all(&destination_path).unwrap();
  10. }
  11. }


从路径可以是一个文件夹或文件,也可以是文件到文件夹到文件夹,但我不知道如何正确删除
main.rs:

  1. if !deleted_files.is_empty() {
  2. for file_path in deleted_files {
  3. remove_file(
  4. source_directory.clone(),
  5. fs::canonicalize(file_path),
  6. backup_directory.clone(),
  7. );
  8. }
  9. }

uplii1fm

uplii1fm1#

这个问题是因为我canonicalize删除了一个文件,这使错误,与使path::PathBuf::from(file_path)的错误已得到修复

相关问题