#directory #iterator #filter #recursion #scan #walk-dir #wildcard

dir-iterator

Iterator that recursively scans and filters files from a directory

5 releases

0.1.4 Nov 17, 2024
0.1.3 Nov 17, 2024
0.1.2 Nov 17, 2024
0.1.1 Nov 14, 2024
0.1.0 Nov 14, 2024

#557 in Filesystem

Download history 130/week @ 2024-11-09 198/week @ 2024-11-16 23/week @ 2024-11-23 1/week @ 2024-11-30 3/week @ 2024-12-07

297 downloads per month

MIT/Apache

13KB
215 lines

dir-iterator

Iterator that recursively scans and filters files from a directory.

Usage

Installation

Start using this library by running the following command in your cargo project directory.

cargo add dir-iterator

Read a Directory Recursively

Read a directory by using DirIterator::build_from_path(path):

use dir_iterator::*;

fn main() {
    // read directory `src`
    DirIterator::build_from_path("src")
        // maybe maybe
        .expect("path not found")
        // print it out
        .for_each(|e| println!("{:?}", e.file_name()));
}

Read Current Directory Recursively

Read current directory by using DirIterator::build_current() is a little shorter because it will panic if current directory does not exist or can't be retrieved.

use dir_iterator::*;

fn main() {
    // build a new iterator starting in the current directory
    DirIterator::build_current()
        // print each file name
        .for_each(|e| println!("{:?}", e.file_name()));
}

You may use DirIterator::try_build_current() to get errors instead of panic.

Filter Result with Wildcards

Filter the result with wildcards by using exclude(wildcard) and which generates a filter.

use dir_iterator::*;

fn main() {
    DirIterator::build_current()
        // filter all files which have extension `txt`
        .filter(exclude("*.txt"))
        .for_each(|e| println!("{:?}", e.file_name()));
}

Ignore Folders When Scanning

To prevent some directories from being scanned at all you ca use ignore(wildcard)

use dir_iterator::*;

fn main() {
    DirIterator::current()
        // ignore target directory
        .ignore("target")
        // ignore all hidden directories
        .ignore(".*")
        // build iterator
        .build()
        // exclude all hidden files
        .filter(exclude(".*"))
        .for_each(|e| println!("{:?}", e.path()));
}

Dependencies

~120KB