3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rustで指定ディレクトリ内の全てのファイルのパスを取得する

Last updated at Posted at 2020-11-05

サンプルコード

use std::error::Error;
use std::fs;
use std::path;

pub fn read_dir(path: &str) -> Result<Vec<path::PathBuf>, Box<dyn Error>> {
    let dir = fs::read_dir(path)?;
    let mut files: Vec<path::PathBuf> = Vec::new();
    for item in dir.into_iter() {
        files.push(item?.path());
    }
    Ok(files)
}

ポイント

let dir = fs::read_dir(path)?;

このときdirはOk(std::fs::ReadDir)型
https://doc.rust-lang.org/std/fs/struct.ReadDir.html
into_iter()によりイテレータとし、パスを順次取得できる


for item in dir.into_iter() {
    files.push(item?.path());
}

ここでitemはstd::fs::DirEntry型
https://doc.rust-lang.org/std/fs/struct.DirEntry.html
path()によりstd::path::PathBuf型でパスを取り出せる

3
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?