Struct Dir

pub struct Dir { pub(in ::fs) inner: Dir }

An object providing access to a directory on the filesystem.

Directories are automatically closed when they go out of scope. Errors detected on closing are ignored by the implementation of Drop.

Platform-specific behavior

On supported systems (including Windows and some UNIX-based OSes), this function acquires a handle/file descriptor for the directory. This allows functions like Dir::open_file to avoid TOCTOU errors when the directory itself is being moved.

On other systems, it stores an absolute path (see [canonicalize()]). In the latter case, no TOCTOU guarantees are made.

Examples

Opens a directory and then a file inside it.

#![feature(dirfd)]
use std::{fs::Dir, io};

fn main() -> std::io::Result<()> {
    let dir = Dir::open("foo")?;
    let mut file = dir.open_file("bar.txt")?;
    let contents = io::read_to_string(file)?;
    assert_eq!(contents, "Hello, world!");
    Ok(())
}

Fields

inner: Dir

Implementations

impl Dir

fn open<P: AsRef<Path>>(path: P) -> Result<Self>

Attempts to open a directory at path in read-only mode.

This function opens a directory. To open a file instead, see File::open.

Errors

This function will return an error if path does not point to an existing directory. Other errors may also be returned according to OpenOptions::open.

Examples

#![feature(dirfd)]
use std::{fs::Dir, io};

fn main() -> std::io::Result<()> {
    let dir = Dir::open("foo")?;
    let mut f = dir.open_file("bar.txt")?;
    let contents = io::read_to_string(f)?;
    assert_eq!(contents, "Hello, world!");
    Ok(())
}
fn open_with<P: AsRef<Path>>(path: P, opts: &OpenOptions) -> Result<Self>

Attempts to open a directory at path according to opts.

This function opens a directory. To open a file instead, see File::open.

Errors

This function will return an error if path does not point to an existing directory. Other errors may also be returned according to OpenOptions::open.

Examples

#![feature(dirfd)]
use std::{fs::{Dir, OpenOptions}, io};

fn main() -> std::io::Result<()> {
    let dir = Dir::open_with("foo", &OpenOptions::new().read(true))?;
    let mut f = dir.open_file("bar.txt")?;
    let contents = io::read_to_string(f)?;
    assert_eq!(contents, "Hello, world!");
    Ok(())
}
fn open_for_traversal<P: AsRef<Path>>(path: P) -> Result<Self>

Attempts to open a directory at path with the minimum permissions for traversal.

The permissions requested by this function are guaranteed to be sufficient to open a child file or folder, but not necessarily to list all children.

Errors

This function may return an error according to OpenOptions::open.

Examples

#![feature(dirfd)]
use std::{fs::Dir, io};

fn main() -> std::io::Result<()> {
    let foo = Dir::open_for_traversal("foo")?;
    let foobar = foo.open_dir("bar")?;
    let mut foobarbaz = foobar.open_file("baz")?;
    let contents = io::read_to_string(foobarbaz)?;
    assert_eq!(contents, "Hello, world!");
    Ok(())
}
fn self_metadata(&self) -> Result<Metadata>

Queries metadata about the underlying directory.

This is equivalent to dir.metadata(".") but can be more efficient.

Examples

#![feature(dirfd)]
use std::fs::Dir;

fn main() -> std::io::Result<()> {
    let dir = Dir::open("foo")?;
    let metadata = dir.self_metadata()?;
    Ok(())
}
fn open_file<P: AsRef<Path>>(&self, path: P) -> Result<File>

Attempts to open a file in read-only mode relative to this directory.

This function interprets path relative to the directory provided by self. To open a file relative to the current working directory, or at an absolute path, see File::open.

Errors

This function will return an error if path does not point to an existing file. Other errors may also be returned according to OpenOptions::open.

Examples

#![feature(dirfd)]
use std::{fs::Dir, io};

fn main() -> std::io::Result<()> {
    let dir = Dir::open("foo")?;
    let mut f = dir.open_file("bar.txt")?;
    let contents = io::read_to_string(f)?;
    assert_eq!(contents, "Hello, world!");
    Ok(())
}
fn open_file_with<P: AsRef<Path>>(&self, path: P, opts: &OpenOptions) -> Result<File>

Attempts to open a file according to opts relative to this directory.

This function interprets path relative to the directory provided by self. To open a file relative to the current working directory, or at an absolute path, see File::open.

Errors

This function will return an error if path does not point to an existing file. Other errors may also be returned according to OpenOptions::open.

Examples

#![feature(dirfd)]
use std::{fs::{Dir, OpenOptions}, io::{self, Write}};

fn main() -> io::Result<()> {
    let dir = Dir::open("foo")?;
    let mut opts = OpenOptions::new();
    opts.read(true).write(true);
    let mut f = dir.open_file_with("bar.txt", &opts)?;
    f.write_all(b"Hello, world!")?;
    let contents = io::read_to_string(f)?;
    assert_eq!(contents, "Hello, world!");
    Ok(())
}
fn remove_file<P: AsRef<Path>>(&self, path: P) -> Result<()>

Attempts to remove a file relative to this directory.

This function interprets path relative to the directory provided by self. To remove a file relative to the current working directory, or at an absolute path, see [fs::remove_file][remove_file].

Errors

This function will return an error if path does not point to an existing file. Other errors may also be returned according to OpenOptions::open.

Examples

#![feature(dirfd)]
use std::fs::Dir;

fn main() -> std::io::Result<()> {
    let dir = Dir::open("foo")?;
    dir.remove_file("bar.txt")?;
    Ok(())
}
fn rename<P: AsRef<Path>, Q: AsRef<Path>>(&self, from: P, to_dir: &Self, to: Q) -> Result<()>

Attempts to rename a file or directory relative to this directory to a new name, replacing the destination file if present.

This function interprets from relative to the directory provided by self and to relative to the directory provided by to_dir. To rename a file relative to the current working directory, or at an absolute path, see [fs::rename][rename].

Errors

This function will return an error if from does not point to an existing file or directory. Other errors may also be returned according to OpenOptions::open.

Examples

#![feature(dirfd)]
use std::fs::Dir;

fn main() -> std::io::Result<()> {
    let dir = Dir::open("foo")?;
    dir.rename("bar.txt", &dir, "quux.txt")?;
    Ok(())
}
fn create_dir<P: AsRef<Path>>(&self, path: P) -> Result<()>

Attempts to create a directory relative to this directory.

This function interprets path relative to the directory provided by self. To create a directory relative to the current working directory, or at an absolute path, see [fs::create_dir][crate::fs::create_dir].

fn open_dir<P: AsRef<Path>>(&self, path: P) -> Result<Self>

Attempts to open a directory in read-only mode relative to this directory.

This function interprets path relative to the directory provided by self. To open a directory relative to the current working directory, or at an absolute path, see Dir::open.

Errors

This function will return an error if path does not point to an existing directory. Other errors may also be returned according to OpenOptions::open.

Examples

#![feature(dirfd)]
use std::{fs::Dir};

fn main() -> std::io::Result<()> {
    let dir = Dir::open("foo")?;
    let foobar = dir.open_dir("bar")?;
    Ok(())
}
fn open_dir_with<P: AsRef<Path>>(&self, path: P, opts: &OpenOptions) -> Result<Self>

Attempts to open a directory relative to this directory according to opts.

This function interprets path relative to the directory provided by self. To open a directory relative to the current working directory, or at an absolute path, see Dir::open.

Errors

This function will return errors according to OpenOptions::open.

Examples

#![feature(dirfd)]
use std::fs::{Dir, OpenOptions};

fn main() -> std::io::Result<()> {
    let dir = Dir::open("foo")?;
    let foobar_w = dir.open_dir_with("bar", &OpenOptions::new().write(true))?;
    Ok(())
}
fn remove_dir<P: AsRef<Path>>(&self, path: P) -> Result<()>

Attempts to remove a directory relative to this directory.

This function interprets path relative to the directory provided by self. To remove a directory relative to the current working directory, or at an absolute path, see [fs::remove_dir][crate::fs::remove_dir].

Errors

This function will return an error if path does not point to an existing directory. Other errors may also be returned according to OpenOptions::open.

Examples

#![feature(dirfd)]
use std::{fs::Dir};

fn main() -> std::io::Result<()> {
    let dir = Dir::open("foo")?;
    dir.remove_dir("bar")?;
    Ok(())
}
fn try_clone(&self) -> Result<Self>

Creates a new Dir instance that shares the same underlying directory handle as the existing Dir instance.

Examples

Creates two handles for a directory named foo:

#![feature(dirfd)]
use std::fs::Dir;

fn main() -> std::io::Result<()> {
    let dir = Dir::open("foo")?;
    let dir_copy = dir.try_clone()?;
    Ok(())
}
fn metadata<P: AsRef<Path>>(&self, path: P) -> Result<Metadata>

Queries the file system to get information about a file, directory, etc. relative to this directory.

This function will traverse symbolic links to query information about the destination file. To query metadata about the path itself without following symbolic links, use [symlink_metadata][Self::symlink_metadata].

Examples

#![feature(dirfd)]
use std::fs::Dir;

fn main() -> std::io::Result<()> {
    let dir = Dir::open("foo")?;
    let metadata = dir.metadata("subdir/file.txt")?;
    Ok(())
}

Queries the file system to get information about a file, directory, etc. relative to this directory.

This function will return the Metadata of the exact path without traversing symbolic links to a resolved destination file. Using this function on a path that is a file or directory (not a symbolic link) will behave the same as [metadata][Self::metadata].

Examples

#![feature(dirfd)]
use std::fs::Dir;

fn main() -> std::io::Result<()> {
    let dir = Dir::open("foo")?;
    let metadata = dir.symlink_metadata("subdir/file.txt")?;
    Ok(())
}

Trait Implementations

impl AsFd for Dir

fn as_fd(&self) -> BorrowedFd<'_>

impl AsInner<Dir> for Dir

fn as_inner(&self) -> &Dir

impl AsRawFd for Dir

fn as_raw_fd(&self) -> RawFd

impl Debug for Dir

fn fmt(&self, f: &mut Formatter<'_>) -> Result

impl From<OwnedFd> for Dir

fn from(value: OwnedFd) -> Self

impl FromInner<Dir> for Dir

fn from_inner(f: Dir) -> Dir

impl FromRawFd for Dir

unsafe fn from_raw_fd(fd: RawFd) -> Self

impl IntoInner<Dir> for Dir

fn into_inner(self) -> Dir

impl IntoRawFd for Dir

fn into_raw_fd(self) -> RawFd

Auto Trait Implementations

impl Freeze for Dir

impl RefUnwindSafe for Dir

impl Send for Dir

impl Sync for Dir

impl Unpin for Dir

impl UnsafeUnpin for Dir

impl UnwindSafe for Dir

Blanket Implementations

impl<T> Any for Dir where T: 'static + ?Sized,

fn type_id(&self) -> TypeId

impl<T> Borrow<T> for Dir where T: ?Sized,

fn borrow(&self) -> &T

impl<T> BorrowMut<T> for Dir where T: ?Sized,

fn borrow_mut(&mut self) -> &mut T

impl<T> From<T> for Dir

fn from(t: T) -> T

Returns the argument unchanged.

impl<T> SizeHint for Dir where T: ?Sized,

fn lower_bound(&self) -> usize
fn upper_bound(&self) -> Option<usize>

impl<T> SizedTypeProperties for Dir

impl<T, U> Into<U> for Dir where U: From<T>,

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

impl<T, U> TryFrom<U> for Dir where U: Into<T>,

type Error = never;
fn try_from(value: U) -> Result<T, never>

impl<T, U> TryInto<U> for Dir where U: TryFrom<T>,

type Error = <U as TryFrom<T>>::Error;
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>