[solved, newbie question] std::path and slice

Hi there !

I'm new to Rust. I want to list all the files from a folder, but I don't want the path appears (only the file names). So I tried to use slice.

In fact, for now, my code works, but I would know whether exist best methods to do what I want because it seems to me ... at least dirty. Btw, I take all tips or remarks on my code :slight_smile:

Here my code :

use std::fs;

fn list_files(pathname: &String)
{
    let paths = fs::read_dir(&pathname).expect("Paths from path");

    for path in paths
    {   
        let s = path.unwrap().path();
        let s = s.to_str().unwrap();
        let s = String::from(s);
        let s = &s[pathname.len()..];

        println!("{}", &s);
    }   
}


fn main()
{
    list_files(&String::from("tiles/"));
}

NB : I know my variable names are stupid.

Path has a file_name function that returns the file's name without the path.

use std::fs;

fn list_files(pathname: &str) {
    let paths = fs::read_dir(pathname).expect("Paths from path");

    for path in paths {
        let s = path.unwrap().file_name();
        let s = s.to_str().unwrap();

        println!("{}", &s);
    }   
}

fn main() {
    list_files(".");
}
1 Like

How could I not see this method reading the doc ? Oo

Thanks for your answer ! <3

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.