I'm new to Rust and have been fighting with this for a while now and I'm sure there's just something about the language that I'm missing. So please excuse me if this obvious.
I'm using the io::stdin().read_line()
to get a path/directory inputed from the user and then use that to loop through the files and/or directories in that entered path.
I'm also setting default path for if the user doesn't enter anything. For this I'm using env::current_dir()
. When I use this default value fs::read_dir()
works fine, but when I try to use the variable set by the user input the system does a panic while running.
let current_directory = env::current_dir().unwrap().display().to_string();
let mut new_directory = String::new();
io::stdin().read_line(&mut new_directory)
.expect("Failed to read line");
let dir = if new_directory == "\n" {
current_directory
} else {
new_directory
};
let paths = fs::read_dir(dir).unwrap();
for path in paths {
println!("Name: {}", path.unwrap().path().display());
}
As I mentioned I get a panic
when it hits the fs::read_dir(dir)
line while the program is running not during while it's compiling.
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error { repr: Os { code: 2, message: "No such file or directory" } }', src/libcore/result.rs:860:4
note: Run with `RUST_BACKTRACE=1` for a backtrace.
and just incase it helps, here's with the backtrace:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error { repr: Os { code: 2, message: "No such file or directory" } }', src/libcore/result.rs:860:4
stack backtrace:
0: std::sys::imp::backtrace::tracing::imp::unwind_backtrace
1: std::panicking::default_hook::{{closure}}
2: std::panicking::default_hook
3: std::panicking::rust_panic_with_hook
4: std::panicking::begin_panic_new
5: std::panicking::begin_panic_fmt
6: rust_begin_unwind
7: core::panicking::panic_fmt
8: core::result::unwrap_failed
9: <core::result::Result<T, E>>::unwrap
10: quad_videos::main
11: __rust_maybe_catch_panic
12: std::rt::lang_start
13: main
Thanks in advance