How to get the current dir in walkdir without using std::env::curren_dir

hi guys!.
so i've been working on these little project and i want to get the current folders files and directories. i use walkdir crate and i'm be able to get the files via providing relative but i can't get the files in the current directory i'm hoping to use '.' for the current directory like use in code . and like vim . but i can't figure out how to do this correctly is there any way good way to do this or crate to achive this?.

use walkdir::{WalkDir,DirEntry};
use std::error::Error;
use std::env::current_dir;

fn is_hidden(entry: &DirEntry) -> bool {

    entry.file_name()
        .to_str()
        .map(|s| s.starts_with("."))
        .unwrap_or(false)
}

pub fn get_dir_files(mut path: String)->Result<(),Box<dyn Error>>{

    if path == "." {
       let pathtwo = current_dir().unwrap();
        path = pathtwo.to_str().unwrap().to_owned();        
        println!("{}",pathtwo.display());
    }
    let walker = WalkDir::new(path).into_iter();
    for entry in walker.filter_entry(|e| !is_hidden(e)) {

        println!("{}",entry?.path().display());
    }

    Ok(())
}

Try passing "./" for the path. This works with Path::new so probably also with WalkDir::new.

Or try: WalkDir::new(Path::new("./"))

1 Like

Just "." will work, except your is_hidden filter is filtering it out. You can fix the filter like this:

fn is_hidden(entry: &DirEntry) -> bool {
    entry.file_name()
        .to_str()
        .map(|s| s.len() > 1 && s.starts_with("."))
        .unwrap_or(false)
}

pub fn get_dir_files(path: &str) -> Result<(),Box<dyn Error>>{
    let walker = WalkDir::new(path).into_iter();
    for entry in walker.filter_entry(|e| !is_hidden(e)) {
        println!("{}",entry?.path().display());
    }
    Ok(())
}

Playground

2 Likes

thank you it worked. what is gonna do the len > 1 in the code?

not working for walkdir

This is filtering out all strings that start with a period except the string "."

1 Like

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.