0

I wanna test if a file gived by an user input, exist with this code :

let mut path_file = String::new();
// input example : path_file = input("C:/Users/.../.../.../file.DAT");
match io::stdin().read_line(&mut path_file) {
    Ok(n) => {
        let path: bool = Path::new(&path_file).exists();
        // let path: bool = Path::new("C:/Users/.../.../.../file.DAT").exists();
        if path {
            read_file_fo(Path::new(&path_file));
        } else {
            println!("...");
        }
    }
    Err(error) => println!("error : {}", error),
}

However, the condition is always false. If I hardcoded directly the path :

let path: bool = Path::new("C:/Users/.../.../.../file.DAT").exists();

instead of :

let path: bool = Path::new(&path_file).exists();

The script run well.

Someone can explain why?

Aplet123
  • 33,825
  • 1
  • 29
  • 55
ExecAssa
  • 177
  • 11

1 Answers1

1

read_line keeps the trailing newline, so trim it off:

let trimmed_path_file = path_file.trim();
let path = Path::new(&trimmed_path_file);
if path.exists() {
    read_file_fo(path);
} else {
    println!("Path does not exist.");
}
Aplet123
  • 33,825
  • 1
  • 29
  • 55