Is there a short (direct) way to get a folder instead of this multi line contraction:
(I am seeking last folder)
let my_dir : PathBuf ;
for component in std::path::Path::new(& std::env::current_dir()?).components().rev() {
my_dir = component ;
break;
}
components()
returns an iterator, just use Iterator::last()
:
let dirname = std::env::current_dir()?.components().last()?;
if the path is a file but you want to get the containing directory, use parent()
.
2 Likes
There is also path.file_name()
which has slightly different semantics but might be suitable for your needs.
let dir_path = std::env::current_dir()?;
let dir_name = dir_path.file_name().unwrap();
(Note: Despite the name, this works fine for directory paths as well as “ordinary file” paths.)
2 Likes
system
Closed
4
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.