std::fs::read_dir

Function std::fs::read_dir

pub fn read_dir<P: AsRef<Path>>(path: P) -> Result<ReadDir>

Returns an iterator over the entries within a directory.

The iterator will yield instances of io::Result<DirEntry>. New errors may be encountered after an iterator is initially constructed.

Platform-specific behavior

This function currently corresponds to the opendir function on Unix and the FindFirstFile function on Windows. Note that, this may change in the future.

Errors

This function will return an error in the following situations, but is not limited to just these cases:

  • The provided path doesn't exist.
  • The process lacks permissions to view the contents.
  • The path points at a non-directory file.

Examples

use std::io;
use std::fs::{self, DirEntry};
use std::path::Path;

// one possible implementation of walking a directory only visiting files
fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
    if dir.is_dir() {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                visit_dirs(&path, cb)?;
            } else {
                cb(&entry);
            }
        }
    }
    Ok(())
}

© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/fs/fn.read_dir.html

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部