fs.rs - source
Description: Source of the Rust file `library/std/src/fs.rs`.

#
std/
fs.rs

    1//! Filesystem manipulation operations.
    2//!
    3//! This module contains basic methods to manipulate the contents of the local
    4//! filesystem. All methods in this module represent cross-platform filesystem
    5//! operations. Extra platform-specific functionality can be found in the
    6//! extension traits of `std::os::$platform`.
    7//!
    8//! # Time of Check to Time of Use (TOCTOU)
    9//!
    10//! Many filesystem operations are subject to a race condition known as "Time of Check to Time of Use"
    11//! (TOCTOU). This occurs when a program checks a condition (like file existence or permissions)
    12//! and then uses the result of that check to make a decision, but the condition may have changed
    13//! between the check and the use.
    14//!
    15//! For example, checking if a file exists and then creating it if it doesn't is vulnerable to
    16//! TOCTOU - another process could create the file between your check and creation attempt.
    17//!
    18//! Another example is with symbolic links: when removing a directory, if another process replaces
    19//! the directory with a symbolic link between the check and the removal operation, the removal
    20//! might affect the wrong location. This is why operations like [`remove_dir_all`] need to use
    21//! atomic operations to prevent such race conditions.
    22//!
    23//! To avoid TOCTOU issues:
    24//! - Be aware that metadata operations (like [`metadata`] or [`symlink_metadata`]) may be affected by
    25//! changes made by other processes.
    26//! - Use atomic operations when possible (like [`File::create_new`] instead of checking existence then creating).
    27//! - Keep file open for the duration of operations.
    28
    29#![stable(feature = "rust1", since = "1.0.0")]
    30#![deny(unsafe_op_in_unsafe_fn)]
    31
    32#[cfg(all(
    33    test,
    34    not(any(
    35        target_os = "emscripten",
    36        target_os = "wasi",
    37        target_env = "sgx",
    38        target_os = "xous",
    39        target_os = "trusty",
    40    ))
    41))]
    42mod tests;
    43
    44use crate::ffi::OsString;
    45use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
    46use crate::path::{Path, PathBuf};
    47use crate::sealed::Sealed;
    48use crate::sync::Arc;
    49use crate::sys::{AsInner, AsInnerMut, FromInner, IntoInner, fs as fs_imp};
    50use crate::time::SystemTime;
    51use crate::{error, fmt};
    52
    53/// An object providing access to an open file on the filesystem.
    54///
    55/// An instance of a `File` can be read and/or written depending on what options
    56/// it was opened with. Files also implement [`Seek`] to alter the logical cursor
    57/// that the file contains internally.
    58///
    59/// Files are automatically closed when they go out of scope.  Errors detected
    60/// on closing are ignored by the implementation of `Drop`.  Use the method
    61/// [`sync_all`] if these errors must be manually handled.
    62///
    63/// `File` does not buffer reads and writes. For efficiency, consider wrapping the
    64/// file in a [`BufReader`] or [`BufWriter`] when performing many small [`read`]
    65/// or [`write`] calls, unless unbuffered reads and writes are required.
    66///
    67/// # Examples
    68///
    69/// Creates a new file and write bytes to it (you can also use [`write`]):
    70///
    71/// ```no_run
    72/// use std::fs::File;
    73/// use std::io::prelude::*;
    74///
    75/// fn main() -> std::io::Result<()> {
    76///     let mut file = File::create("foo.txt")?;
    77///     file.write_all(b"Hello, world!")?;
    78///     Ok(())
    79/// }
    80/// ```
    81///
    82/// Reads the contents of a file into a [`String`] (you can also use [`read`]):
    83///
    84/// ```no_run
    85/// use std::fs::File;
    86/// use std::io::prelude::*;
    87///
    88/// fn main() -> std::io::Result<()> {
    89///     let mut file = File::open("foo.txt")?;
    90///     let mut contents = String::new();
    91///     file.read_to_string(&mut contents)?;
    92///     assert_eq!(contents, "Hello, world!");
    93///     Ok(())
    94/// }
    95/// ```
    96///
    97/// Using a buffered [`Read`]er:
    98///
    99/// ```no_run
    100/// use std::fs::File;
    101/// use std::io::BufReader;
    102/// use std::io::prelude::*;
    103///
    104/// fn main() -> std::io::Result<()> {
    105///     let file = File::open("foo.txt")?;
    106///     let mut buf_reader = BufReader::new(file);
    107///     let mut contents = String::new();
    108///     buf_reader.read_to_string(&mut contents)?;
    109///     assert_eq!(contents, "Hello, world!");
    110///     Ok(())
    111/// }
    112/// ```
    113///
    114/// Note that, although read and write methods require a `&mut File`, because
    115/// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
    116/// still modify the file, either through methods that take `&File` or by
    117/// retrieving the underlying OS object and modifying the file that way.
    118/// Additionally, many operating systems allow concurrent modification of files
    119/// by different processes. Avoid assuming that holding a `&File` means that the
    120/// file will not change.
    121///
    122/// # Platform-specific behavior
    123///
    124/// On Windows, the implementation of [`Read`] and [`Write`] traits for `File`
    125/// perform synchronous I/O operations. Therefore the underlying file must not
    126/// have been opened for asynchronous I/O (e.g. by using `FILE_FLAG_OVERLAPPED`).
    127///
    128/// [`BufReader`]: io::BufReader
    129/// [`BufWriter`]: io::BufWriter
    130/// [`sync_all`]: File::sync_all
    131/// [`write`]: File::write
    132/// [`read`]: File::read
    133#[stable(feature = "rust1", since = "1.0.0")]
    134#[cfg_attr(not(test), rustc_diagnostic_item = "File")]
    135pub struct File {
    136    inner: fs_imp::File,
    137}
    138
    139/// An enumeration of possible errors which can occur while trying to acquire a lock
    140/// from the [`try_lock`] method and [`try_lock_shared`] method on a [`File`].
    141///
    142/// [`try_lock`]: File::try_lock
    143/// [`try_lock_shared`]: File::try_lock_shared
    144#[stable(feature = "file_lock", since = "1.89.0")]
    145pub enum TryLockError {
    146    /// The lock could not be acquired due to an I/O error on the file. The standard library will
    147    /// not return an [`ErrorKind::WouldBlock`] error inside [`TryLockError::Error`]
    148    ///
    149    /// [`ErrorKind::WouldBlock`]: io::ErrorKind::WouldBlock
    150    Error(io::Error),
    151    /// The lock could not be acquired at this time because it is held by another handle/process.
    152    WouldBlock,
    153}
    154
    155/// An object providing access to a directory on the filesystem.
    156///
    157/// Directories are automatically closed when they go out of scope.  Errors detected
    158/// on closing are ignored by the implementation of `Drop`.
    159///
    160/// # Platform-specific behavior
    161///
    162/// On supported systems (including Windows and some UNIX-based OSes), this function acquires a
    163/// handle/file descriptor for the directory. This allows functions like [`Dir::open_file`] to
    164/// avoid [TOCTOU] errors when the directory itself is being moved.
    165///
    166/// On other systems, it stores an absolute path (see [`canonicalize()`]). In the latter case, no
    167/// [TOCTOU] guarantees are made.
    168///
    169/// # Examples
    170///
    171/// Opens a directory and then a file inside it.
    172///
    173/// ```no_run
    174/// #![feature(dirfd)]
    175/// use std::{fs::Dir, io};
    176///
    177/// fn main() -> std::io::Result<()> {
    178///     let dir = Dir::open("foo")?;
    179///     let mut file = dir.open_file("bar.txt")?;
    180///     let contents = io::read_to_string(file)?;
    181///     assert_eq!(contents, "Hello, world!");
    182///     Ok(())
    183/// }
    184/// ```
    185///
    186/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
    187#[unstable(feature = "dirfd", issue = "120426")]
    188pub struct Dir {
    189    inner: fs_imp::Dir,
    190}
    191
    192/// Metadata information about a file.
    193///
    194/// This structure is returned from the [`metadata`] or
    195/// [`symlink_metadata`] function or method and represents known
    196/// metadata about a file such as its permissions, size, modification
    197/// times, etc.
    198#[stable(feature = "rust1", since = "1.0.0")]
    199#[derive(Clone)]
    200pub struct Metadata(fs_imp::FileAttr);
    201
    202/// Iterator over the entries in a directory.
    203///
    204/// This iterator is returned from the [`read_dir`] function of this module and
    205/// will yield instances of <code>[io::Result]<[DirEntry]></code>. Through a [`DirEntry`]
    206/// information like the entry's path and possibly other metadata can be
    207/// learned.
    208///
    209/// The order in which this iterator returns entries is platform and filesystem
    210/// dependent.
    211///
    212/// # Errors
    213/// This [`io::Result`] will be an [`Err`] if an error occurred while fetching
    214/// the next entry from the OS.
    215#[stable(feature = "rust1", since = "1.0.0")]
    216#[derive(Debug)]
    217pub struct ReadDir(fs_imp::ReadDir);
    218
    219/// Entries returned by the [`ReadDir`] iterator.
    220///
    221/// An instance of `DirEntry` represents an entry inside of a directory on the
    222/// filesystem. Each entry can be inspected via methods to learn about the full
    223/// path or possibly other metadata through per-platform extension traits.
    224///
    225/// # Platform-specific behavior
    226///
    227/// On Unix, the `DirEntry` struct contains an internal reference to the open
    228/// directory. Holding `DirEntry` objects will consume a file handle even
    229/// after the `ReadDir` iterator is dropped.
    230///
    231/// Note that this [may change in the future][changes].
    232///
    233/// [changes]: io#platform-specific-behavior
    234#[stable(feature = "rust1", since = "1.0.0")]
    235pub struct DirEntry(fs_imp::DirEntry);
    236
    237/// Options and flags which can be used to configure how a file is opened.
    238///
    239/// This builder exposes the ability to configure how a [`File`] is opened and
    240/// what operations are permitted on the open file. The [`File::open`] and
    241/// [`File::create`] methods are aliases for commonly used options using this
    242/// builder.
    243///
    244/// Generally speaking, when using `OpenOptions`, you'll first call
    245/// [`OpenOptions::new`], then chain calls to methods to set each option, then
    246/// call [`OpenOptions::open`], passing the path of the file you're trying to
    247/// open. This will give you a [`io::Result`] with a [`File`] inside that you
    248/// can further operate on.
    249///
    250/// # Examples
    251///
    252/// Opening a file to read:
    253///
    254/// ```no_run
    255/// use std::fs::OpenOptions;
    256///
    257/// let file = OpenOptions::new().read(true).open("foo.txt");
    258/// ```
    259///
    260/// Opening a file for both reading and writing, as well as creating it if it
    261/// doesn't exist:
    262///
    263/// ```no_run
    264/// use std::fs::OpenOptions;
    265///
    266/// let file = OpenOptions::new()
    267///             .read(true)
    268///             .write(true)
    269///             .create(true)
    270///             .open("foo.txt");
    271/// ```
    272#[derive(Clone, Debug)]
    273#[stable(feature = "rust1", since = "1.0.0")]
    274#[cfg_attr(not(test), rustc_diagnostic_item = "FsOpenOptions")]
    275pub struct OpenOptions(fs_imp::OpenOptions);
    276
    277/// Representation of the various timestamps on a file.
    278#[derive(Copy, Clone, Debug, Default)]
    279#[stable(feature = "file_set_times", since = "1.75.0")]
    280pub struct FileTimes(fs_imp::FileTimes);
    281
    282/// Representation of the various permissions on a file.
    283///
    284/// This module only currently provides one bit of information,
    285/// [`Permissions::readonly`], which is exposed on all currently supported
    286/// platforms. Unix-specific functionality, such as mode bits, is available
    287/// through the [`PermissionsExt`] trait.
    288///
    289/// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
    290#[derive(Clone, PartialEq, Eq, Debug)]
    291#[stable(feature = "rust1", since = "1.0.0")]
    292#[cfg_attr(not(test), rustc_diagnostic_item = "FsPermissions")]
    293pub struct Permissions(fs_imp::FilePermissions);
    294
    295/// A structure representing a type of file with accessors for each file type.
    296/// It is returned by [`Metadata::file_type`] method.
    297#[stable(feature = "file_type", since = "1.1.0")]
    298#[derive(Copy, Clone, PartialEq, Eq, Hash)]
    299#[cfg_attr(not(test), rustc_diagnostic_item = "FileType")]
    300pub struct FileType(fs_imp::FileType);
    301
    302/// A builder used to create directories in various manners.
    303///
    304/// This builder also supports platform-specific options.
    305#[stable(feature = "dir_builder", since = "1.6.0")]
    306#[cfg_attr(not(test), rustc_diagnostic_item = "DirBuilder")]
    307#[derive(Debug)]
    308pub struct DirBuilder {
    309    inner: fs_imp::DirBuilder,
    310    recursive: bool,
    311}
    312
    313/// Reads the entire contents of a file into a bytes vector.
    314///
    315/// This is a convenience function for using [`File::open`] and [`read_to_end`]
    316/// with fewer imports and without an intermediate variable.
    317///
    318/// [`read_to_end`]: Read::read_to_end
    319///
    320/// # Errors
    321///
    322/// This function will return an error if `path` does not already exist.
    323/// Other errors may also be returned according to [`OpenOptions::open`].
    324///
    325/// While reading from the file, this function handles [`io::ErrorKind::Interrupted`]
    326/// with automatic retries. See [io::Read] documentation for details.
    327///
    328/// # Examples
    329///
    330/// ```no_run
    331/// use std::fs;
    332///
    333/// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
    334///     let data: Vec<u8> = fs::read("image.jpg")?;
    335///     assert_eq!(data[0..3], [0xFF, 0xD8, 0xFF]);
    336///     Ok(())
    337/// }
    338/// ```
    339#[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
    340pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
    341    fn inner(path: &Path) -> io::Result<Vec<u8>> {
    342        let mut file = File::open(path)?;
    343        let size = file.metadata().map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)).ok();
    344        let mut bytes = Vec::try_with_capacity(size.unwrap_or(0))?;
    345        io::default_read_to_end(&mut file, &mut bytes, size)?;
    346        Ok(bytes)
    347    }
    348    inner(path.as_ref())
    349}
    350
    351/// Reads the entire contents of a file into a string.
    352///
    353/// This is a convenience function for using [`File::open`] and [`read_to_string`]
    354/// with fewer imports and without an intermediate variable.
    355///
    356/// [`read_to_string`]: Read::read_to_string
    357///
    358/// # Errors
    359///
    360/// This function will return an error if `path` does not already exist.
    361/// Other errors may also be returned according to [`OpenOptions::open`].
    362///
    363/// If the contents of the file are not valid UTF-8, then an error will also be
    364/// returned.
    365///
    366/// While reading from the file, this function handles [`io::ErrorKind::Interrupted`]
    367/// with automatic retries. See [io::Read] documentation for details.
    368///
    369/// # Examples
    370///
    371/// ```no_run
    372/// use std::fs;
    373/// use std::error::Error;
    374///
    375/// fn main() -> Result<(), Box<dyn Error>> {
    376///     let message: String = fs::read_to_string("message.txt")?;
    377///     println!("{}", message);
    378///     Ok(())
    379/// }
    380/// ```
    381#[stable(feature = "fs_read_write", since = "1.26.0")]
    382pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
    383    fn inner(path: &Path) -> io::Result<String> {
    384        let mut file = File::open(path)?;
    385        let size = file.metadata().map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)).ok();
    386        let mut string = String::new();
    387        string.try_reserve_exact(size.unwrap_or(0))?;
    388        io::default_read_to_string(&mut file, &mut string, size)?;
    389        Ok(string)
    390    }
    391    inner(path.as_ref())
    392}
    393
    394/// Writes a slice as the entire contents of a file.
    395///
    396/// This function will create a file if it does not exist,
    397/// and will entirely replace its contents if it does.
    398///
    399/// Depending on the platform, this function may fail if the
    400/// full directory path does not exist.
    401///
    402/// This is a convenience function for using [`File::create`] and [`write_all`]
    403/// with fewer imports.
    404///
    405/// [`write_all`]: Write::write_all
    406///
    407/// # Examples
    408///
    409/// ```no_run
    410/// use std::fs;
    411///
    412/// fn main() -> std::io::Result<()> {
    413///     fs::write("foo.txt", b"Lorem ipsum")?;
    414///     fs::write("bar.txt", "dolor sit")?;
    415///     Ok(())
    416/// }
    417/// ```
    418#[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
    419pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
    420    fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
    421        File::create(path)?.write_all(contents)
    422    }
    423    inner(path.as_ref(), contents.as_ref())
    424}
    425
    426/// Changes the timestamps of the file or directory at the specified path.
    427///
    428/// This function will attempt to set the access and modification times
    429/// to the times specified. If the path refers to a symbolic link, this function
    430/// will follow the link and change the timestamps of the target file.
    431///
    432/// # Platform-specific behavior
    433///
    434/// This function currently corresponds to the `utimensat` function on Unix platforms, the
    435/// `setattrlist` function on Apple platforms, and the `SetFileTime` function on Windows.
    436///
    437/// # Errors
    438///
    439/// This function will return an error if the user lacks permission to change timestamps on the
    440/// target file or symlink. It may also return an error if the OS does not support it.
    441///
    442/// # Examples
    443///
    444/// ```no_run
    445/// #![feature(fs_set_times)]
    446/// use std::fs::{self, FileTimes};
    447/// use std::time::SystemTime;
    448///
    449/// fn main() -> std::io::Result<()> {
    450///     let now = SystemTime::now();
    451///     let times = FileTimes::new()
    452///         .set_accessed(now)
    453///         .set_modified(now);
    454///     fs::set_times("foo.txt", times)?;
    455///     Ok(())
    456/// }
    457/// ```
    458#[unstable(feature = "fs_set_times", issue = "147455")]
    459#[doc(alias = "utimens")]
    460#[doc(alias = "utimes")]
    461#[doc(alias = "utime")]
    462pub fn set_times<P: AsRef<Path>>(path: P, times: FileTimes) -> io::Result<()> {
    463    fs_imp::set_times(path.as_ref(), times.0)
    464}
    465
    466/// Changes the timestamps of the file or symlink at the specified path.
    467///
    468/// This function will attempt to set the access and modification times
    469/// to the times specified. Differ from `set_times`, if the path refers to a symbolic link,
    470/// this function will change the timestamps of the symlink itself, not the target file.
    471///
    472/// # Platform-specific behavior
    473///
    474/// This function currently corresponds to the `utimensat` function with `AT_SYMLINK_NOFOLLOW` on
    475/// Unix platforms, the `setattrlist` function with `FSOPT_NOFOLLOW` on Apple platforms, and the
    476/// `SetFileTime` function on Windows.
    477///
    478/// # Errors
    479///
    480/// This function will return an error if the user lacks permission to change timestamps on the
    481/// target file or symlink. It may also return an error if the OS does not support it.
    482///
    483/// # Examples
    484///
    485/// ```no_run
    486/// #![feature(fs_set_times)]
    487/// use std::fs::{self, FileTimes};
    488/// use std::time::SystemTime;
    489///
    490/// fn main() -> std::io::Result<()> {
    491///     let now = SystemTime::now();
    492///     let times = FileTimes::new()
    493///         .set_accessed(now)
    494///         .set_modified(now);
    495///     fs::set_times_nofollow("symlink.txt", times)?;
    496///     Ok(())
    497/// }
    498/// ```
    499#[unstable(feature = "fs_set_times", issue = "147455")]
    500#[doc(alias = "utimensat")]
    501#[doc(alias = "lutimens")]
    502#[doc(alias = "lutimes")]
    503pub fn set_times_nofollow<P: AsRef<Path>>(path: P, times: FileTimes) -> io::Result<()> {
    504    fs_imp::set_times_nofollow(path.as_ref(), times.0)
    505}
    506
    507#[stable(feature = "file_lock", since = "1.89.0")]
    508impl error::Error for TryLockError {}
    509
    510#[stable(feature = "file_lock", since = "1.89.0")]
    511impl fmt::Debug for TryLockError {
    512    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    513        match self {
    514            TryLockError::Error(err) => err.fmt(f),
    515            TryLockError::WouldBlock => "WouldBlock".fmt(f),
    516        }
    517    }
    518}
    519
    520#[stable(feature = "file_lock", since = "1.89.0")]
    521impl fmt::Display for TryLockError {
    522    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    523        match self {
    524            TryLockError::Error(_) => "lock acquisition failed due to I/O error",
    525            TryLockError::WouldBlock => "lock acquisition failed because the operation would block",
    526        }
    527        .fmt(f)
    528    }
    529}
    530
    531#[stable(feature = "file_lock", since = "1.89.0")]
    532impl From<TryLockError> for io::Error {
    533    fn from(err: TryLockError) -> io::Error {
    534        match err {
    535            TryLockError::Error(err) => err,
    536            TryLockError::WouldBlock => io::ErrorKind::WouldBlock.into(),
    537        }
    538    }
    539}
    540
    541impl File {
    542    /// Attempts to open a file in read-only mode.
    543    ///
    544    /// See the [`OpenOptions::open`] method for more details.
    545    ///
    546    /// If you only need to read the entire file contents,
    547    /// consider [`std::fs::read()`][self::read] or
    548    /// [`std::fs::read_to_string()`][self::read_to_string] instead.
    549    ///
    550    /// # Errors
    551    ///
    552    /// This function will return an error if `path` does not already exist.
    553    /// Other errors may also be returned according to [`OpenOptions::open`].
    554    ///
    555    /// # Examples
    556    ///
    557    /// ```no_run
    558    /// use std::fs::File;
    559    /// use std::io::Read;
    560    ///
    561    /// fn main() -> std::io::Result<()> {
    562    ///     let mut f = File::open("foo.txt")?;
    563    ///     let mut data = vec![];
    564    ///     f.read_to_end(&mut data)?;
    565    ///     Ok(())
    566    /// }
    567    /// ```
    568    #[stable(feature = "rust1", since = "1.0.0")]
    569    pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
    570        OpenOptions::new().read(true).open(path.as_ref())
    571    }
    572
    573    /// Attempts to open a file in read-only mode with buffering.
    574    ///
    575    /// See the [`OpenOptions::open`] method, the [`BufReader`][io::BufReader] type,
    576    /// and the [`BufRead`][io::BufRead] trait for more details.
    577    ///
    578    /// If you only need to read the entire file contents,
    579    /// consider [`std::fs::read()`][self::read] or
    580    /// [`std::fs::read_to_string()`][self::read_to_string] instead.
    581    ///
    582    /// # Errors
    583    ///
    584    /// This function will return an error if `path` does not already exist,
    585    /// or if memory allocation fails for the new buffer.
    586    /// Other errors may also be returned according to [`OpenOptions::open`].
    587    ///
    588    /// # Examples
    589    ///
    590    /// ```no_run
    591    /// #![feature(file_buffered)]
    592    /// use std::fs::File;
    593    /// use std::io::BufRead;
    594    ///
    595    /// fn main() -> std::io::Result<()> {
    596    ///     let mut f = File::open_buffered("foo.txt")?;
    597    ///     assert!(f.capacity() > 0);
    598    ///     for (line, i) in f.lines().zip(1..) {
    599    ///         println!("{i:6}: {}", line?);
    600    ///     }
    601    ///     Ok(())
    602    /// }
    603    /// ```
    604    #[unstable(feature = "file_buffered", issue = "130804")]
    605    pub fn open_buffered<P: AsRef<Path>>(path: P) -> io::Result<io::BufReader<File>> {
    606        // Allocate the buffer *first* so we don't affect the filesystem otherwise.
    607        let buffer = io::BufReader::<Self>::try_new_buffer()?;
    608        let file = File::open(path)?;
    609        Ok(io::BufReader::with_buffer(file, buffer))
    610    }
    611
    612    /// Opens a file in write-only mode.
    613    ///
    614    /// This function will create a file if it does not exist,
    615    /// and will truncate it if it does.
    616    ///
    617    /// Depending on the platform, this function may fail if the
    618    /// full directory path does not exist.
    619    /// See the [`OpenOptions::open`] function for more details.
    620    ///
    621    /// See also [`std::fs::write()`][self::write] for a simple function to
    622    /// create a file with some given data.
    623    ///
    624    /// # Examples
    625    ///
    626    /// ```no_run
    627    /// use std::fs::File;
    628    /// use std::io::Write;
    629    ///
    630    /// fn main() -> std::io::Result<()> {
    631    ///     let mut f = File::create("foo.txt")?;
    632    ///     f.write_all(&1234_u32.to_be_bytes())?;
    633    ///     Ok(())
    634    /// }
    635    /// ```
    636    #[stable(feature = "rust1", since = "1.0.0")]
    637    pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
    638        OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
    639    }
    640
    641    /// Opens a file in write-only mode with buffering.
    642    ///
    643    /// This function will create a file if it does not exist,
    644    /// and will truncate it if it does.
    645    ///
    646    /// Depending on the platform, this function may fail if the
    647    /// full directory path does not exist.
    648    ///
    649    /// See the [`OpenOptions::open`] method and the
    650    /// [`BufWriter`][io::BufWriter] type for more details.
    651    ///
    652    /// See also [`std::fs::write()`][self::write] for a simple function to
    653    /// create a file with some given data.
    654    ///
    655    /// # Examples
    656    ///
    657    /// ```no_run
    658    /// #![feature(file_buffered)]
    659    /// use std::fs::File;
    660    /// use std::io::Write;
    661    ///
    662    /// fn main() -> std::io::Result<()> {
    663    ///     let mut f = File::create_buffered("foo.txt")?;
    664    ///     assert!(f.capacity() > 0);
    665    ///     for i in 0..100 {
    666    ///         writeln!(&mut f, "{i}")?;
    667    ///     }
    668    ///     f.flush()?;
    669    ///     Ok(())
    670    /// }
    671    /// ```
    672    #[unstable(feature = "file_buffered", issue = "130804")]
    673    pub fn create_buffered<P: AsRef<Path>>(path: P) -> io::Result<io::BufWriter<File>> {
    674        // Allocate the buffer *first* so we don't affect the filesystem otherwise.
    675        let buffer = io::BufWriter::<Self>::try_new_buffer()?;
    676        let file = File::create(path)?;
    677        Ok(io::BufWriter::with_buffer(file, buffer))
    678    }
    679
    680    /// Creates a new file in read-write mode; error if the file exists.
    681    ///
    682    /// This function will create a file if it does not exist, or return an error if it does. This
    683    /// way, if the call succeeds, the file returned is guaranteed to be new.
    684    /// If a file exists at the target location, creating a new file will fail with [`AlreadyExists`]
    685    /// or another error based on the situation. See [`OpenOptions::open`] for a
    686    /// non-exhaustive list of likely errors.
    687    ///
    688    /// This option is useful because it is atomic. Otherwise between checking whether a file
    689    /// exists and creating a new one, the file may have been created by another process (a [TOCTOU]
    690    /// race condition / attack).
    691    ///
    692    /// This can also be written using
    693    /// `File::options().read(true).write(true).create_new(true).open(...)`.
    694    ///
    695    /// [`AlreadyExists`]: crate::io::ErrorKind::AlreadyExists
    696    /// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
    697    ///
    698    /// # Examples
    699    ///
    700    /// ```no_run
    701    /// use std::fs::File;
    702    /// use std::io::Write;
    703    ///
    704    /// fn main() -> std::io::Result<()> {
    705    ///     let mut f = File::create_new("foo.txt")?;
    706    ///     f.write_all("Hello, world!".as_bytes())?;
    707    ///     Ok(())
    708    /// }
    709    /// ```
    710    #[stable(feature = "file_create_new", since = "1.77.0")]
    711    pub fn create_new<P: AsRef<Path>>(path: P) -> io::Result<File> {
    712        OpenOptions::new().read(true).write(true).create_new(true).open(path.as_ref())
    713    }
    714
    715    /// Returns a new OpenOptions object.
    716    ///
    717    /// This function returns a new OpenOptions object that you can use to
    718    /// open or create a file with specific options if `open()` or `create()`
    719    /// are not appropriate.
    720    ///
    721    /// It is equivalent to `OpenOptions::new()`, but allows you to write more
    722    /// readable code. Instead of
    723    /// `OpenOptions::new().append(true).open("example.log")`,
    724    /// you can write `File::options().append(true).open("example.log")`. This
    725    /// also avoids the need to import `OpenOptions`.
    726    ///
    727    /// See the [`OpenOptions::new`] function for more details.
    728    ///
    729    /// # Examples
    730    ///
    731    /// ```no_run
    732    /// use std::fs::File;
    733    /// use std::io::Write;
    734    ///
    735    /// fn main() -> std::io::Result<()> {
    736    ///     let mut f = File::options().append(true).open("example.log")?;
    737    ///     writeln!(&mut f, "new line")?;
    738    ///     Ok(())
    739    /// }
    740    /// ```
    741    #[must_use]
    742    #[stable(feature = "with_options", since = "1.58.0")]
    743    #[cfg_attr(not(test), rustc_diagnostic_item = "file_options")]
    744    pub fn options() -> OpenOptions {
    745        OpenOptions::new()
    746    }
    747
    748    /// Attempts to sync all OS-internal file content and metadata to disk.
    749    ///
    750    /// This function will attempt to ensure that all in-memory data reaches the
    751    /// filesystem before returning.
    752    ///
    753    /// This can be used to handle errors that would otherwise only be caught
    754    /// when the `File` is closed, as dropping a `File` will ignore all errors.
    755    /// Note, however, that `sync_all` is generally more expensive than closing
    756    /// a file by dropping it, because the latter is not required to block until
    757    /// the data has been written to the filesystem.
    758    ///
    759    /// If synchronizing the metadata is not required, use [`sync_data`] instead.
    760    ///
    761    /// [`sync_data`]: File::sync_data
    762    ///
    763    /// # Examples
    764    ///
    765    /// ```no_run
    766    /// use std::fs::File;
    767    /// use std::io::prelude::*;
    768    ///
    769    /// fn main() -> std::io::Result<()> {
    770    ///     let mut f = File::create("foo.txt")?;
    771    ///     f.write_all(b"Hello, world!")?;
    772    ///
    773    ///     f.sync_all()?;
    774    ///     Ok(())
    775    /// }
    776    /// ```
    777    #[stable(feature = "rust1", since = "1.0.0")]
    778    #[doc(alias = "fsync")]
    779    pub fn sync_all(&self) -> io::Result<()> {
    780        self.inner.fsync()
    781    }
    782
    783    /// This function is similar to [`sync_all`], except that it might not
    784    /// synchronize file metadata to the filesystem.
    785    ///
    786    /// This is intended for use cases that must synchronize content, but don't
    787    /// need the metadata on disk. The goal of this method is to reduce disk
    788    /// operations.
    789    ///
    790    /// Note that some platforms may simply implement this in terms of
    791    /// [`sync_all`].
    792    ///
    793    /// [`sync_all`]: File::sync_all
    794    ///
    795    /// # Examples
    796    ///
    797    /// ```no_run
    798    /// use std::fs::File;
    799    /// use std::io::prelude::*;
    800    ///
    801    /// fn main() -> std::io::Result<()> {
    802    ///     let mut f = File::create("foo.txt")?;
    803    ///     f.write_all(b"Hello, world!")?;
    804    ///
    805    ///     f.sync_data()?;
    806    ///     Ok(())
    807    /// }
    808    /// ```
    809    #[stable(feature = "rust1", since = "1.0.0")]
    810    #[doc(alias = "fdatasync")]
    811    pub fn sync_data(&self) -> io::Result<()> {
    812        self.inner.datasync()
    813    }
    814
    815    /// Acquire an exclusive lock on the file. Blocks until the lock can be acquired.
    816    ///
    817    /// This acquires an exclusive lock; no other file handle to this file may acquire another lock.
    818    ///
    819    /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
    820    /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
    821    /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
    822    /// cause non-lockholders to block.
    823    ///
    824    /// If this file handle/descriptor, or a clone of it, already holds a lock the exact behavior
    825    /// is unspecified and platform dependent, including the possibility that it will deadlock.
    826    /// However, if this method returns, then an exclusive lock is held.
    827    ///
    828    /// If the file is not open for writing, it is unspecified whether this function returns an error.
    829    ///
    830    /// The lock will be released when this file (along with any other file descriptors/handles
    831    /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
    832    ///
    833    /// # Platform-specific behavior
    834    ///
    835    /// This function currently corresponds to the `flock` function on Unix with the `LOCK_EX` flag,
    836    /// and the `LockFileEx` function on Windows with the `LOCKFILE_EXCLUSIVE_LOCK` flag. Note that,
    837    /// this [may change in the future][changes].
    838    ///
    839    /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
    840    /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
    841    ///
    842    /// [changes]: io#platform-specific-behavior
    843    ///
    844    /// [`lock`]: File::lock
    845    /// [`lock_shared`]: File::lock_shared
    846    /// [`try_lock`]: File::try_lock
    847    /// [`try_lock_shared`]: File::try_lock_shared
    848    /// [`unlock`]: File::unlock
    849    /// [`read`]: Read::read
    850    /// [`write`]: Write::write
    851    ///
    852    /// # Examples
    853    ///
    854    /// ```no_run
    855    /// use std::fs::File;
    856    ///
    857    /// fn main() -> std::io::Result<()> {
    858    ///     let f = File::create("foo.txt")?;
    859    ///     f.lock()?;
    860    ///     Ok(())
    861    /// }
    862    /// ```
    863    #[stable(feature = "file_lock", since = "1.89.0")]
    864    pub fn lock(&self) -> io::Result<()> {
    865        self.inner.lock()
    866    }
    867
    868    /// Acquire a shared (non-exclusive) lock on the file. Blocks until the lock can be acquired.
    869    ///
    870    /// This acquires a shared lock; more than one file handle may hold a shared lock, but none may
    871    /// hold an exclusive lock at the same time.
    872    ///
    873    /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
    874    /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
    875    /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
    876    /// cause non-lockholders to block.
    877    ///
    878    /// If this file handle/descriptor, or a clone of it, already holds a lock, the exact behavior
    879    /// is unspecified and platform dependent, including the possibility that it will deadlock.
    880    /// However, if this method returns, then a shared lock is held.
    881    ///
    882    /// The lock will be released when this file (along with any other file descriptors/handles
    883    /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
    884    ///
    885    /// # Platform-specific behavior
    886    ///
    887    /// This function currently corresponds to the `flock` function on Unix with the `LOCK_SH` flag,
    888    /// and the `LockFileEx` function on Windows. Note that, this
    889    /// [may change in the future][changes].
    890    ///
    891    /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
    892    /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
    893    ///
    894    /// [changes]: io#platform-specific-behavior
    895    ///
    896    /// [`lock`]: File::lock
    897    /// [`lock_shared`]: File::lock_shared
    898    /// [`try_lock`]: File::try_lock
    899    /// [`try_lock_shared`]: File::try_lock_shared
    900    /// [`unlock`]: File::unlock
    901    /// [`read`]: Read::read
    902    /// [`write`]: Write::write
    903    ///
    904    /// # Examples
    905    ///
    906    /// ```no_run
    907    /// use std::fs::File;
    908    ///
    909    /// fn main() -> std::io::Result<()> {
    910    ///     let f = File::open("foo.txt")?;
    911    ///     f.lock_shared()?;
    912    ///     Ok(())
    913    /// }
    914    /// ```
    915    #[stable(feature = "file_lock", since = "1.89.0")]
    916    pub fn lock_shared(&self) -> io::Result<()> {
    917        self.inner.lock_shared()
    918    }
    919
    920    /// Try to acquire an exclusive lock on the file.
    921    ///
    922    /// Returns `Err(TryLockError::WouldBlock)` if a different lock is already held on this file
    923    /// (via another handle/descriptor).
    924    ///
    925    /// This acquires an exclusive lock; no other file handle to this file may acquire another lock.
    926    ///
    927    /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
    928    /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
    929    /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
    930    /// cause non-lockholders to block.
    931    ///
    932    /// If this file handle/descriptor, or a clone of it, already holds a lock, the exact behavior
    933    /// is unspecified and platform dependent, including the possibility that it will deadlock.
    934    /// However, if this method returns `Ok(())`, then it has acquired an exclusive lock.
    935    ///
    936    /// If the file is not open for writing, it is unspecified whether this function returns an error.
    937    ///
    938    /// The lock will be released when this file (along with any other file descriptors/handles
    939    /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
    940    ///
    941    /// # Platform-specific behavior
    942    ///
    943    /// This function currently corresponds to the `flock` function on Unix with the `LOCK_EX` and
    944    /// `LOCK_NB` flags, and the `LockFileEx` function on Windows with the `LOCKFILE_EXCLUSIVE_LOCK`
    945    /// and `LOCKFILE_FAIL_IMMEDIATELY` flags. Note that, this
    946    /// [may change in the future][changes].
    947    ///
    948    /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
    949    /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
    950    ///
    951    /// [changes]: io#platform-specific-behavior
    952    ///
    953    /// [`lock`]: File::lock
    954    /// [`lock_shared`]: File::lock_shared
    955    /// [`try_lock`]: File::try_lock
    956    /// [`try_lock_shared`]: File::try_lock_shared
    957    /// [`unlock`]: File::unlock
    958    /// [`read`]: Read::read
    959    /// [`write`]: Write::write
    960    ///
    961    /// # Examples
    962    ///
    963    /// ```no_run
    964    /// use std::fs::{File, TryLockError};
    965    ///
    966    /// fn main() -> std::io::Result<()> {
    967    ///     let f = File::create("foo.txt")?;
    968    ///     // Explicit handling of the WouldBlock error
    969    ///     match f.try_lock() {
    970    ///         Ok(_) => (),
    971    ///         Err(TryLockError::WouldBlock) => (), // Lock not acquired
    972    ///         Err(TryLockError::Error(err)) => return Err(err),
    973    ///     }
    974    ///     // Alternately, propagate the error as an io::Error
    975    ///     f.try_lock()?;
    976    ///     Ok(())
    977    /// }
    978    /// ```
    979    #[stable(feature = "file_lock", since = "1.89.0")]
    980    pub fn try_lock(&self) -> Result<(), TryLockError> {
    981        self.inner.try_lock()
    982    }
    983
    984    /// Try to acquire a shared (non-exclusive) lock on the file.
    985    ///
    986    /// Returns `Err(TryLockError::WouldBlock)` if a different lock is already held on this file
    987    /// (via another handle/descriptor).
    988    ///
    989    /// This acquires a shared lock; more than one file handle may hold a shared lock, but none may
    990    /// hold an exclusive lock at the same time.
    991    ///
    992    /// This lock may be advisory or mandatory. This lock is meant to interact with [`lock`],
    993    /// [`try_lock`], [`lock_shared`], [`try_lock_shared`], and [`unlock`]. Its interactions with
    994    /// other methods, such as [`read`] and [`write`] are platform specific, and it may or may not
    995    /// cause non-lockholders to block.
    996    ///
    997    /// If this file handle, or a clone of it, already holds a lock, the exact behavior is
    998    /// unspecified and platform dependent, including the possibility that it will deadlock.
    999    /// However, if this method returns `Ok(())`, then it has acquired a shared lock.
    1000    ///
    1001    /// The lock will be released when this file (along with any other file descriptors/handles
    1002    /// duplicated or inherited from it) is closed, or if the [`unlock`] method is called.
    1003    ///
    1004    /// # Platform-specific behavior
    1005    ///
    1006    /// This function currently corresponds to the `flock` function on Unix with the `LOCK_SH` and
    1007    /// `LOCK_NB` flags, and the `LockFileEx` function on Windows with the
    1008    /// `LOCKFILE_FAIL_IMMEDIATELY` flag. Note that, this
    1009    /// [may change in the future][changes].
    1010    ///
    1011    /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
    1012    /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
    1013    ///
    1014    /// [changes]: io#platform-specific-behavior
    1015    ///
    1016    /// [`lock`]: File::lock
    1017    /// [`lock_shared`]: File::lock_shared
    1018    /// [`try_lock`]: File::try_lock
    1019    /// [`try_lock_shared`]: File::try_lock_shared
    1020    /// [`unlock`]: File::unlock
    1021    /// [`read`]: Read::read
    1022    /// [`write`]: Write::write
    1023    ///
    1024    /// # Examples
    1025    ///
    1026    /// ```no_run
    1027    /// use std::fs::{File, TryLockError};
    1028    ///
    1029    /// fn main() -> std::io::Result<()> {
    1030    ///     let f = File::open("foo.txt")?;
    1031    ///     // Explicit handling of the WouldBlock error
    1032    ///     match f.try_lock_shared() {
    1033    ///         Ok(_) => (),
    1034    ///         Err(TryLockError::WouldBlock) => (), // Lock not acquired
    1035    ///         Err(TryLockError::Error(err)) => return Err(err),
    1036    ///     }
    1037    ///     // Alternately, propagate the error as an io::Error
    1038    ///     f.try_lock_shared()?;
    1039    ///
    1040    ///     Ok(())
    1041    /// }
    1042    /// ```
    1043    #[stable(feature = "file_lock", since = "1.89.0")]
    1044    pub fn try_lock_shared(&self) -> Result<(), TryLockError> {
    1045        self.inner.try_lock_shared()
    1046    }
    1047
    1048    /// Release all locks on the file.
    1049    ///
    1050    /// All locks are released when the file (along with any other file descriptors/handles
    1051    /// duplicated or inherited from it) is closed. This method allows releasing locks without
    1052    /// closing the file.
    1053    ///
    1054    /// If no lock is currently held via this file descriptor/handle, this method may return an
    1055    /// error, or may return successfully without taking any action.
    1056    ///
    1057    /// # Platform-specific behavior
    1058    ///
    1059    /// This function currently corresponds to the `flock` function on Unix with the `LOCK_UN` flag,
    1060    /// and the `UnlockFile` function on Windows. Note that, this
    1061    /// [may change in the future][changes].
    1062    ///
    1063    /// On Windows, locking a file will fail if the file is opened only for append. To lock a file,
    1064    /// open it with one of `.read(true)`, `.read(true).append(true)`, or `.write(true)`.
    1065    ///
    1066    /// [changes]: io#platform-specific-behavior
    1067    ///
    1068    /// # Examples
    1069    ///
    1070    /// ```no_run
    1071    /// use std::fs::File;
    1072    ///
    1073    /// fn main() -> std::io::Result<()> {
    1074    ///     let f = File::open("foo.txt")?;
    1075    ///     f.lock()?;
    1076    ///     f.unlock()?;
    1077    ///     Ok(())
    1078    /// }
    1079    /// ```
    1080    #[stable(feature = "file_lock", since = "1.89.0")]
    1081    pub fn unlock(&self) -> io::Result<()> {
    1082        self.inner.unlock()
    1083    }
    1084
    1085    /// Truncates or extends the underlying file, updating the size of
    1086    /// this file to become `size`.
    1087    ///
    1088    /// If the `size` is less than the current file's size, then the file will
    1089    /// be shrunk. If it is greater than the current file's size, then the file
    1090    /// will be extended to `size` and have all of the intermediate data filled
    1091    /// in with 0s.
    1092    ///
    1093    /// The file's cursor isn't changed. In particular, if the cursor was at the
    1094    /// end and the file is shrunk using this operation, the cursor will now be
    1095    /// past the end.
    1096    ///
    1097    /// # Errors
    1098    ///
    1099    /// This function will return an error if the file is not opened for writing.
    1100    /// Also, [`std::io::ErrorKind::InvalidInput`](crate::io::ErrorKind::InvalidInput)
    1101    /// will be returned if the desired length would cause an overflow due to
    1102    /// the implementation specifics.
    1103    ///
    1104    /// # Examples
    1105    ///
    1106    /// ```no_run
    1107    /// use std::fs::File;
    1108    ///
    1109    /// fn main() -> std::io::Result<()> {
    1110    ///     let mut f = File::create("foo.txt")?;
    1111    ///     f.set_len(10)?;
    1112    ///     Ok(())
    1113    /// }
    1114    /// ```
    1115    ///
    1116    /// Note that this method alters the content of the underlying file, even
    1117    /// though it takes `&self` rather than `&mut self`.
    1118    #[stable(feature = "rust1", since = "1.0.0")]
    1119    pub fn set_len(&self, size: u64) -> io::Result<()> {
    1120        self.inner.truncate(size)
    1121    }
    1122
    1123    /// Queries metadata about the underlying file.
    1124    ///
    1125    /// # Examples
    1126    ///
    1127    /// ```no_run
    1128    /// use std::fs::File;
    1129    ///
    1130    /// fn main() -> std::io::Result<()> {
    1131    ///     let mut f = File::open("foo.txt")?;
    1132    ///     let metadata = f.metadata()?;
    1133    ///     Ok(())
    1134    /// }
    1135    /// ```
    1136    #[stable(feature = "rust1", since = "1.0.0")]
    1137    pub fn metadata(&self) -> io::Result<Metadata> {
    1138        self.inner.file_attr().map(Metadata)
    1139    }
    1140
    1141    /// Creates a new `File` instance that shares the same underlying file handle
    1142    /// as the existing `File` instance. Reads, writes, and seeks will affect
    1143    /// both `File` instances simultaneously.
    1144    ///
    1145    /// # Examples
    1146    ///
    1147    /// Creates two handles for a file named `foo.txt`:
    1148    ///
    1149    /// ```no_run
    1150    /// use std::fs::File;
    1151    ///
    1152    /// fn main() -> std::io::Result<()> {
    1153    ///     let mut file = File::open("foo.txt")?;
    1154    ///     let file_copy = file.try_clone()?;
    1155    ///     Ok(())
    1156    /// }
    1157    /// ```
    1158    ///
    1159    /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
    1160    /// two handles, seek one of them, and read the remaining bytes from the
    1161    /// other handle:
    1162    ///
    1163    /// ```no_run
    1164    /// use std::fs::File;
    1165    /// use std::io::SeekFrom;
    1166    /// use std::io::prelude::*;
    1167    ///
    1168    /// fn main() -> std::io::Result<()> {
    1169    ///     let mut file = File::open("foo.txt")?;
    1170    ///     let mut file_copy = file.try_clone()?;
    1171    ///
    1172    ///     file.seek(SeekFrom::Start(3))?;
    1173    ///
    1174    ///     let mut contents = vec![];
    1175    ///     file_copy.read_to_end(&mut contents)?;
    1176    ///     assert_eq!(contents, b"def\n");
    1177    ///     Ok(())
    1178    /// }
    1179    /// ```
    1180    #[stable(feature = "file_try_clone", since = "1.9.0")]
    1181    pub fn try_clone(&self) -> io::Result<File> {
    1182        Ok(File { inner: self.inner.duplicate()? })
    1183    }
    1184
    1185    /// Changes the permissions on the underlying file.
    1186    ///
    1187    /// # Platform-specific behavior
    1188    ///
    1189    /// This function currently corresponds to the `fchmod` function on Unix and
    1190    /// the `SetFileInformationByHandle` function on Windows. Note that, this
    1191    /// [may change in the future][changes].
    1192    ///
    1193    /// [changes]: io#platform-specific-behavior
    1194    ///
    1195    /// # Errors
    1196    ///
    1197    /// This function will return an error if the user lacks permission change
    1198    /// attributes on the underlying file. It may also return an error in other
    1199    /// os-specific unspecified cases.
    1200    ///
    1201    /// # Examples
    1202    ///
    1203    /// ```no_run
    1204    /// fn main() -> std::io::Result<()> {
    1205    ///     use std::fs::File;
    1206    ///
    1207    ///     let file = File::open("foo.txt")?;
    1208    ///     let mut perms = file.metadata()?.permissions();
    1209    ///     perms.set_readonly(true);
    1210    ///     file.set_permissions(perms)?;
    1211    ///     Ok(())
    1212    /// }
    1213    /// ```
    1214    ///
    1215    /// Note that this method alters the permissions of the underlying file,
    1216    /// even though it takes `&self` rather than `&mut self`.
    1217    #[doc(alias = "fchmod", alias = "SetFileInformationByHandle")]
    1218    #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
    1219    pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
    1220        self.inner.set_permissions(perm.0)
    1221    }
    1222
    1223    /// Changes the timestamps of the underlying file.
    1224    ///
    1225    /// # Platform-specific behavior
    1226    ///
    1227    /// This function currently corresponds to the `futimens` function on Unix (falling back to
    1228    /// `futimes` on macOS before 10.13) and the `SetFileTime` function on Windows. Note that this
    1229    /// [may change in the future][changes].
    1230    ///
    1231    /// On most platforms, including UNIX and Windows platforms, this function can also change the
    1232    /// timestamps of a directory. To get a `File` representing a directory in order to call
    1233    /// `set_times`, open the directory with `File::open` without attempting to obtain write
    1234    /// permission.
    1235    ///
    1236    /// [changes]: io#platform-specific-behavior
    1237    ///
    1238    /// # Errors
    1239    ///
    1240    /// This function will return an error if the user lacks permission to change timestamps on the
    1241    /// underlying file. It may also return an error in other os-specific unspecified cases.
    1242    ///
    1243    /// This function may return an error if the operating system lacks support to change one or
    1244    /// more of the timestamps set in the `FileTimes` structure.
    1245    ///
    1246    /// # Examples
    1247    ///
    1248    /// ```no_run
    1249    /// fn main() -> std::io::Result<()> {
    1250    ///     use std::fs::{self, File, FileTimes};
    1251    ///
    1252    ///     let src = fs::metadata("src")?;
    1253    ///     let dest = File::open("dest")?;
    1254    ///     let times = FileTimes::new()
    1255    ///         .set_accessed(src.accessed()?)
    1256    ///         .set_modified(src.modified()?);
    1257    ///     dest.set_times(times)?;
    1258    ///     Ok(())
    1259    /// }
    1260    /// ```
    1261    #[stable(feature = "file_set_times", since = "1.75.0")]
    1262    #[doc(alias = "futimens")]
    1263    #[doc(alias = "futimes")]
    1264    #[doc(alias = "SetFileTime")]
    1265    pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
    1266        self.inner.set_times(times.0)
    1267    }
    1268
    1269    /// Changes the modification time of the underlying file.
    1270    ///
    1271    /// This is an alias for `set_times(FileTimes::new().set_modified(time))`.
    1272    #[stable(feature = "file_set_times", since = "1.75.0")]
    1273    #[inline]
    1274    pub fn set_modified(&self, time: SystemTime) -> io::Result<()> {
    1275        self.set_times(FileTimes::new().set_modified(time))
    1276    }
    1277}
    1278
    1279// In addition to the `impl`s here, `File` also has `impl`s for
    1280// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
    1281// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
    1282// `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
    1283// `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
    1284
    1285impl AsInner<fs_imp::File> for File {
    1286    #[inline]
    1287    fn as_inner(&self) -> &fs_imp::File {
    1288        &self.inner
    1289    }
    1290}
    1291impl FromInner<fs_imp::File> for File {
    1292    fn from_inner(f: fs_imp::File) -> File {
    1293        File { inner: f }
    1294    }
    1295}
    1296impl IntoInner<fs_imp::File> for File {
    1297    fn into_inner(self) -> fs_imp::File {
    1298        self.inner
    1299    }
    1300}
    1301
    1302#[stable(feature = "rust1", since = "1.0.0")]
    1303impl fmt::Debug for File {
    1304    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    1305        self.inner.fmt(f)
    1306    }
    1307}
    1308
    1309/// Indicates how much extra capacity is needed to read the rest of the file.
    1310fn buffer_capacity_required(mut file: &File) -> Option<usize> {
    1311    let size = file.metadata().map(|m| m.len()).ok()?;
    1312    let pos = file.stream_position().ok()?;
    1313    // Don't worry about `usize` overflow because reading will fail regardless
    1314    // in that case.
    1315    Some(size.saturating_sub(pos) as usize)
    1316}
    1317
    1318#[stable(feature = "rust1", since = "1.0.0")]
    1319impl Read for &File {
    1320    /// Reads some bytes from the file.
    1321    ///
    1322    /// See [`Read::read`] docs for more info.
    1323    ///
    1324    /// # Platform-specific behavior
    1325    ///
    1326    /// This function currently corresponds to the `read` function on Unix and
    1327    /// the `NtReadFile` function on Windows. Note that this [may change in
    1328    /// the future][changes].
    1329    ///
    1330    /// [changes]: io#platform-specific-behavior
    1331    #[inline]
    1332    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
    1333        self.inner.read(buf)
    1334    }
    1335
    1336    /// Like `read`, except that it reads into a slice of buffers.
    1337    ///
    1338    /// See [`Read::read_vectored`] docs for more info.
    1339    ///
    1340    /// # Platform-specific behavior
    1341    ///
    1342    /// This function currently corresponds to the `readv` function on Unix and
    1343    /// falls back to the `read` implementation on Windows. Note that this
    1344    /// [may change in the future][changes].
    1345    ///
    1346    /// [changes]: io#platform-specific-behavior
    1347    #[inline]
    1348    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
    1349        self.inner.read_vectored(bufs)
    1350    }
    1351
    1352    #[inline]
    1353    fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
    1354        self.inner.read_buf(cursor)
    1355    }
    1356
    1357    /// Determines if `File` has an efficient `read_vectored` implementation.
    1358    ///
    1359    /// See [`Read::is_read_vectored`] docs for more info.
    1360    ///
    1361    /// # Platform-specific behavior
    1362    ///
    1363    /// This function currently returns `true` on Unix and `false` on Windows.
    1364    /// Note that this [may change in the future][changes].
    1365    ///
    1366    /// [changes]: io#platform-specific-behavior
    1367    #[inline]
    1368    fn is_read_vectored(&self) -> bool {
    1369        self.inner.is_read_vectored()
    1370    }
    1371
    1372    // Reserves space in the buffer based on the file size when available.
    1373    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
    1374        let size = buffer_capacity_required(self);
    1375        buf.try_reserve(size.unwrap_or(0))?;
    1376        io::default_read_to_end(self, buf, size)
    1377    }
    1378
    1379    // Reserves space in the buffer based on the file size when available.
    1380    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
    1381        let size = buffer_capacity_required(self);
    1382        buf.try_reserve(size.unwrap_or(0))?;
    1383        io::default_read_to_string(self, buf, size)
    1384    }
    1385}
    1386#[stable(feature = "rust1", since = "1.0.0")]
    1387impl Write for &File {
    1388    /// Writes some bytes to the file.
    1389    ///
    1390    /// See [`Write::write`] docs for more info.
    1391    ///
    1392    /// # Platform-specific behavior
    1393    ///
    1394    /// This function currently corresponds to the `write` function on Unix and
    1395    /// the `NtWriteFile` function on Windows. Note that this [may change in
    1396    /// the future][changes].
    1397    ///
    1398    /// [changes]: io#platform-specific-behavior
    1399    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
    1400        self.inner.write(buf)
    1401    }
    1402
    1403    /// Like `write`, except that it writes into a slice of buffers.
    1404    ///
    1405    /// See [`Write::write_vectored`] docs for more info.
    1406    ///
    1407    /// # Platform-specific behavior
    1408    ///
    1409    /// This function currently corresponds to the `writev` function on Unix
    1410    /// and falls back to the `write` implementation on Windows. Note that this
    1411    /// [may change in the future][changes].
    1412    ///
    1413    /// [changes]: io#platform-specific-behavior
    1414    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
    1415        self.inner.write_vectored(bufs)
    1416    }
    1417
    1418    /// Determines if `File` has an efficient `write_vectored` implementation.
    1419    ///
    1420    /// See [`Write::is_write_vectored`] docs for more info.
    1421    ///
    1422    /// # Platform-specific behavior
    1423    ///
    1424    /// This function currently returns `true` on Unix and `false` on Windows.
    1425    /// Note that this [may change in the future][changes].
    1426    ///
    1427    /// [changes]: io#platform-specific-behavior
    1428    #[inline]
    1429    fn is_write_vectored(&self) -> bool {
    1430        self.inner.is_write_vectored()
    1431    }
    1432
    1433    /// Flushes the file, ensuring that all intermediately buffered contents
    1434    /// reach their destination.
    1435    ///
    1436    /// See [`Write::flush`] docs for more info.
    1437    ///
    1438    /// # Platform-specific behavior
    1439    ///
    1440    /// Since a `File` structure doesn't contain any buffers, this function is
    1441    /// currently a no-op on Unix and Windows. Note that this [may change in
    1442    /// the future][changes].
    1443    ///
    1444    /// [changes]: io#platform-specific-behavior
    1445    #[inline]
    1446    fn flush(&mut self) -> io::Result<()> {
    1447        self.inner.flush()
    1448    }
    1449}
    1450#[stable(feature = "rust1", since = "1.0.0")]
    1451impl Seek for &File {
    1452    /// Seek to an offset, in bytes in a file.
    1453    ///
    1454    /// See [`Seek::seek`] docs for more info.
    1455    ///
    1456    /// # Platform-specific behavior
    1457    ///
    1458    /// This function currently corresponds to the `lseek64` function on Unix
    1459    /// and the `SetFilePointerEx` function on Windows. Note that this [may
    1460    /// change in the future][changes].
    1461    ///
    1462    /// [changes]: io#platform-specific-behavior
    1463    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
    1464        self.inner.seek(pos)
    1465    }
    1466
    1467    /// Returns the length of this file (in bytes).
    1468    ///
    1469    /// See [`Seek::stream_len`] docs for more info.
    1470    ///
    1471    /// # Platform-specific behavior
    1472    ///
    1473    /// This function currently corresponds to the `statx` function on Linux
    1474    /// (with fallbacks) and the `GetFileSizeEx` function on Windows. Note that
    1475    /// this [may change in the future][changes].
    1476    ///
    1477    /// [changes]: io#platform-specific-behavior
    1478    fn stream_len(&mut self) -> io::Result<u64> {
    1479        if let Some(result) = self.inner.size() {
    1480            return result;
    1481        }
    1482        io::stream_len_default(self)
    1483    }
    1484
    1485    fn stream_position(&mut self) -> io::Result<u64> {
    1486        self.inner.tell()
    1487    }
    1488}
    1489
    1490#[stable(feature = "rust1", since = "1.0.0")]
    1491impl Read for File {
    1492    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
    1493        (&*self).read(buf)
    1494    }
    1495    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
    1496        (&*self).read_vectored(bufs)
    1497    }
    1498    fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
    1499        (&*self).read_buf(cursor)
    1500    }
    1501    #[inline]
    1502    fn is_read_vectored(&self) -> bool {
    1503        (&&*self).is_read_vectored()
    1504    }
    1505    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
    1506        (&*self).read_to_end(buf)
    1507    }
    1508    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
    1509        (&*self).read_to_string(buf)
    1510    }
    1511}
    1512#[stable(feature = "rust1", since = "1.0.0")]
    1513impl Write for File {
    1514    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
    1515        (&*self).write(buf)
    1516    }
    1517    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
    1518        (&*self).write_vectored(bufs)
    1519    }
    1520    #[inline]
    1521    fn is_write_vectored(&self) -> bool {
    1522        (&&*self).is_write_vectored()
    1523    }
    1524    #[inline]
    1525    fn flush(&mut self) -> io::Result<()> {
    1526        (&*self).flush()
    1527    }
    1528}
    1529#[stable(feature = "rust1", since = "1.0.0")]
    1530impl Seek for File {
    1531    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
    1532        (&*self).seek(pos)
    1533    }
    1534    fn stream_len(&mut self) -> io::Result<u64> {
    1535        (&*self).stream_len()
    1536    }
    1537    fn stream_position(&mut self) -> io::Result<u64> {
    1538        (&*self).stream_position()
    1539    }
    1540}
    1541
    1542#[stable(feature = "io_traits_arc", since = "1.73.0")]
    1543impl Read for Arc<File> {
    1544    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
    1545        (&**self).read(buf)
    1546    }
    1547    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
    1548        (&**self).read_vectored(bufs)
    1549    }
    1550    fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
    1551        (&**self).read_buf(cursor)
    1552    }
    1553    #[inline]
    1554    fn is_read_vectored(&self) -> bool {
    1555        (&**self).is_read_vectored()
    1556    }
    1557    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
    1558        (&**self).read_to_end(buf)
    1559    }
    1560    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
    1561        (&**self).read_to_string(buf)
    1562    }
    1563}
    1564#[stable(feature = "io_traits_arc", since = "1.73.0")]
    1565impl Write for Arc<File> {
    1566    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
    1567        (&**self).write(buf)
    1568    }
    1569    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
    1570        (&**self).write_vectored(bufs)
    1571    }
    1572    #[inline]
    1573    fn is_write_vectored(&self) -> bool {
    1574        (&**self).is_write_vectored()
    1575    }
    1576    #[inline]
    1577    fn flush(&mut self) -> io::Result<()> {
    1578        (&**self).flush()
    1579    }
    1580}
    1581#[stable(feature = "io_traits_arc", since = "1.73.0")]
    1582impl Seek for Arc<File> {
    1583    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
    1584        (&**self).seek(pos)
    1585    }
    1586    fn stream_len(&mut self) -> io::Result<u64> {
    1587        (&**self).stream_len()
    1588    }
    1589    fn stream_position(&mut self) -> io::Result<u64> {
    1590        (&**self).stream_position()
    1591    }
    1592}
    1593
    1594impl Dir {
    1595    /// Attempts to open a directory at `path` in read-only mode.
    1596    ///
    1597    /// # Errors
    1598    ///
    1599    /// This function will return an error if `path` does not point to an existing directory.
    1600    /// Other errors may also be returned according to [`OpenOptions::open`].
    1601    ///
    1602    /// # Examples
    1603    ///
    1604    /// ```no_run
    1605    /// #![feature(dirfd)]
    1606    /// use std::{fs::Dir, io};
    1607    ///
    1608    /// fn main() -> std::io::Result<()> {
    1609    ///     let dir = Dir::open("foo")?;
    1610    ///     let mut f = dir.open_file("bar.txt")?;
    1611    ///     let contents = io::read_to_string(f)?;
    1612    ///     assert_eq!(contents, "Hello, world!");
    1613    ///     Ok(())
    1614    /// }
    1615    /// ```
    1616    #[unstable(feature = "dirfd", issue = "120426")]
    1617    pub fn open<P: AsRef<Path>>(path: P) -> io::Result<Self> {
    1618        fs_imp::Dir::open(path.as_ref(), &OpenOptions::new().read(true).0)
    1619            .map(|inner| Self { inner })
    1620    }
    1621
    1622    /// Attempts to open a file in read-only mode relative to this directory.
    1623    ///
    1624    /// # Errors
    1625    ///
    1626    /// This function will return an error if `path` does not point to an existing file.
    1627    /// Other errors may also be returned according to [`OpenOptions::open`].
    1628    ///
    1629    /// # Examples
    1630    ///
    1631    /// ```no_run
    1632    /// #![feature(dirfd)]
    1633    /// use std::{fs::Dir, io};
    1634    ///
    1635    /// fn main() -> std::io::Result<()> {
    1636    ///     let dir = Dir::open("foo")?;
    1637    ///     let mut f = dir.open_file("bar.txt")?;
    1638    ///     let contents = io::read_to_string(f)?;
    1639    ///     assert_eq!(contents, "Hello, world!");
    1640    ///     Ok(())
    1641    /// }
    1642    /// ```
    1643    #[unstable(feature = "dirfd", issue = "120426")]
    1644    pub fn open_file<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
    1645        self.inner
    1646            .open_file(path.as_ref(), &OpenOptions::new().read(true).0)
    1647            .map(|f| File { inner: f })
    1648    }
    1649}
    1650
    1651impl AsInner<fs_imp::Dir> for Dir {
    1652    #[inline]
    1653    fn as_inner(&self) -> &fs_imp::Dir {
    1654        &self.inner
    1655    }
    1656}
    1657impl FromInner<fs_imp::Dir> for Dir {
    1658    fn from_inner(f: fs_imp::Dir) -> Dir {
    1659        Dir { inner: f }
    1660    }
    1661}
    1662impl IntoInner<fs_imp::Dir> for Dir {
    1663    fn into_inner(self) -> fs_imp::Dir {
    1664        self.inner
    1665    }
    1666}
    1667
    1668#[unstable(feature = "dirfd", issue = "120426")]
    1669impl fmt::Debug for Dir {
    1670    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    1671        self.inner.fmt(f)
    1672    }
    1673}
    1674
    1675impl OpenOptions {
    1676    /// Creates a blank new set of options ready for configuration.
    1677    ///
    1678    /// All options are initially set to `false`.
    1679    ///
    1680    /// # Examples
    1681    ///
    1682    /// ```no_run
    1683    /// use std::fs::OpenOptions;
    1684    ///
    1685    /// let mut options = OpenOptions::new();
    1686    /// let file = options.read(true).open("foo.txt");
    1687    /// ```
    1688    #[cfg_attr(not(test), rustc_diagnostic_item = "open_options_new")]
    1689    #[stable(feature = "rust1", since = "1.0.0")]
    1690    #[must_use]
    1691    pub fn new() -> Self {
    1692        OpenOptions(fs_imp::OpenOptions::new())
    1693    }
    1694
    1695    /// Sets the option for read access.
    1696    ///
    1697    /// This option, when true, will indicate that the file should be
    1698    /// `read`-able if opened.
    1699    ///
    1700    /// # Examples
    1701    ///
    1702    /// ```no_run
    1703    /// use std::fs::OpenOptions;
    1704    ///
    1705    /// let file = OpenOptions::new().read(true).open("foo.txt");
    1706    /// ```
    1707    #[stable(feature = "rust1", since = "1.0.0")]
    1708    pub fn read(&mut self, read: bool) -> &mut Self {
    1709        self.0.read(read);
    1710        self
    1711    }
    1712
    1713    /// Sets the option for write access.
    1714    ///
    1715    /// This option, when true, will indicate that the file should be
    1716    /// `write`-able if opened.
    1717    ///
    1718    /// If the file already exists, any write calls on it will overwrite its
    1719    /// contents, without truncating it.
    1720    ///
    1721    /// # Examples
    1722    ///
    1723    /// ```no_run
    1724    /// use std::fs::OpenOptions;
    1725    ///
    1726    /// let file = OpenOptions::new().write(true).open("foo.txt");
    1727    /// ```
    1728    #[stable(feature = "rust1", since = "1.0.0")]
    1729    pub fn write(&mut self, write: bool) -> &mut Self {
    1730        self.0.write(write);
    1731        self
    1732    }
    1733
    1734    /// Sets the option for the append mode.
    1735    ///
    1736    /// This option, when true, means that writes will append to a file instead
    1737    /// of overwriting previous contents.
    1738    /// Note that setting `.write(true).append(true)` has the same effect as
    1739    /// setting only `.append(true)`.
    1740    ///
    1741    /// Append mode guarantees that writes will be positioned at the current end of file,
    1742    /// even when there are other processes or threads appending to the same file. This is
    1743    /// unlike <code>[seek]\([SeekFrom]::[End]\(0))</code> followed by `write()`, which
    1744    /// has a race between seeking and writing during which another writer can write, with
    1745    /// our `write()` overwriting their data.
    1746    ///
    1747    /// Keep in mind that this does not necessarily guarantee that data appended by
    1748    /// different processes or threads does not interleave. The amount of data accepted a
    1749    /// single `write()` call depends on the operating system and file system. A
    1750    /// successful `write()` is allowed to write only part of the given data, so even if
    1751    /// you're careful to provide the whole message in a single call to `write()`, there
    1752    /// is no guarantee that it will be written out in full. If you rely on the filesystem
    1753    /// accepting the message in a single write, make sure that all data that belongs
    1754    /// together is written in one operation. This can be done by concatenating strings
    1755    /// before passing them to [`write()`].
    1756    ///
    1757    /// If a file is opened with both read and append access, beware that after
    1758    /// opening, and after every write, the position for reading may be set at the
    1759    /// end of the file. So, before writing, save the current position (using
    1760    /// <code>[Seek]::[stream_position]</code>), and restore it before the next read.
    1761    ///
    1762    /// ## Note
    1763    ///
    1764    /// This function doesn't create the file if it doesn't exist. Use the
    1765    /// [`OpenOptions::create`] method to do so.
    1766    ///
    1767    /// [`write()`]: Write::write "io::Write::write"
    1768    /// [`flush()`]: Write::flush "io::Write::flush"
    1769    /// [stream_position]: Seek::stream_position "io::Seek::stream_position"
    1770    /// [seek]: Seek::seek "io::Seek::seek"
    1771    /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
    1772    /// [End]: SeekFrom::End "io::SeekFrom::End"
    1773    ///
    1774    /// # Examples
    1775    ///
    1776    /// ```no_run
    1777    /// use std::fs::OpenOptions;
    1778    ///
    1779    /// let file = OpenOptions::new().append(true).open("foo.txt");
    1780    /// ```
    1781    #[stable(feature = "rust1", since = "1.0.0")]
    1782    pub fn append(&mut self, append: bool) -> &mut Self {
    1783        self.0.append(append);
    1784        self
    1785    }
    1786
    1787    /// Sets the option for truncating a previous file.
    1788    ///
    1789    /// If a file is successfully opened with this option set to true, it will truncate
    1790    /// the file to 0 length if it already exists.
    1791    ///
    1792    /// The file must be opened with write access for truncate to work.
    1793    ///
    1794    /// # Examples
    1795    ///
    1796    /// ```no_run
    1797    /// use std::fs::OpenOptions;
    1798    ///
    1799    /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
    1800    /// ```
    1801    #[stable(feature = "rust1", since = "1.0.0")]
    1802    pub fn truncate(&mut self, truncate: bool) -> &mut Self {
    1803        self.0.truncate(truncate);
    1804        self
    1805    }
    1806
    1807    /// Sets the option to create a new file, or open it if it already exists.
    1808    ///
    1809    /// In order for the file to be created, [`OpenOptions::write`] or
    1810    /// [`OpenOptions::append`] access must be used.
    1811    ///
    1812    /// See also [`std::fs::write()`][self::write] for a simple function to
    1813    /// create a file with some given data.
    1814    ///
    1815    /// # Errors
    1816    ///
    1817    /// If `.create(true)` is set without `.write(true)` or `.append(true)`,
    1818    /// calling [`open`](Self::open) will fail with [`InvalidInput`](io::ErrorKind::InvalidInput) error.
    1819    /// # Examples
    1820    ///
    1821    /// ```no_run
    1822    /// use std::fs::OpenOptions;
    1823    ///
    1824    /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
    1825    /// ```
    1826    #[stable(feature = "rust1", since = "1.0.0")]
    1827    pub fn create(&mut self, create: bool) -> &mut Self {
    1828        self.0.create(create);
    1829        self
    1830    }
    1831
    1832    /// Sets the option to create a new file, failing if it already exists.
    1833    ///
    1834    /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
    1835    /// way, if the call succeeds, the file returned is guaranteed to be new.
    1836    /// If a file exists at the target location, creating a new file will fail with [`AlreadyExists`]
    1837    /// or another error based on the situation. See [`OpenOptions::open`] for a
    1838    /// non-exhaustive list of likely errors.
    1839    ///
    1840    /// This option is useful because it is atomic. Otherwise between checking
    1841    /// whether a file exists and creating a new one, the file may have been
    1842    /// created by another process (a [TOCTOU] race condition / attack).
    1843    ///
    1844    /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
    1845    /// ignored.
    1846    ///
    1847    /// The file must be opened with write or append access in order to create
    1848    /// a new file.
    1849    ///
    1850    /// [`.create()`]: OpenOptions::create
    1851    /// [`.truncate()`]: OpenOptions::truncate
    1852    /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
    1853    /// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
    1854    ///
    1855    /// # Examples
    1856    ///
    1857    /// ```no_run
    1858    /// use std::fs::OpenOptions;
    1859    ///
    1860    /// let file = OpenOptions::new().write(true)
    1861    ///                              .create_new(true)
    1862    ///                              .open("foo.txt");
    1863    /// ```
    1864    #[stable(feature = "expand_open_options2", since = "1.9.0")]
    1865    pub fn create_new(&mut self, create_new: bool) -> &mut Self {
    1866        self.0.create_new(create_new);
    1867        self
    1868    }
    1869
    1870    /// Opens a file at `path` with the options specified by `self`.
    1871    ///
    1872    /// # Errors
    1873    ///
    1874    /// This function will return an error under a number of different
    1875    /// circumstances. Some of these error conditions are listed here, together
    1876    /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
    1877    /// part of the compatibility contract of the function.
    1878    ///
    1879    /// * [`NotFound`]: The specified file does not exist and neither `create`
    1880    ///   or `create_new` is set.
    1881    /// * [`NotFound`]: One of the directory components of the file path does
    1882    ///   not exist.
    1883    /// * [`PermissionDenied`]: The user lacks permission to get the specified
    1884    ///   access rights for the file.
    1885    /// * [`PermissionDenied`]: The user lacks permission to open one of the
    1886    ///   directory components of the specified path.
    1887    /// * [`AlreadyExists`]: `create_new` was specified and the file already
    1888    ///   exists.
    1889    /// * [`InvalidInput`]: Invalid combinations of open options (truncate
    1890    ///   without write access, create without write or append access,
    1891    ///   no access mode set, etc.).
    1892    ///
    1893    /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
    1894    /// * One of the directory components of the specified file path
    1895    ///   was not, in fact, a directory.
    1896    /// * Filesystem-level errors: full disk, write permission
    1897    ///   requested on a read-only file system, exceeded disk quota, too many
    1898    ///   open files, too long filename, too many symbolic links in the
    1899    ///   specified path (Unix-like systems only), etc.
    1900    ///
    1901    /// # Examples
    1902    ///
    1903    /// ```no_run
    1904    /// use std::fs::OpenOptions;
    1905    ///
    1906    /// let file = OpenOptions::new().read(true).open("foo.txt");
    1907    /// ```
    1908    ///
    1909    /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
    1910    /// [`InvalidInput`]: io::ErrorKind::InvalidInput
    1911    /// [`NotFound`]: io::ErrorKind::NotFound
    1912    /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
    1913    #[stable(feature = "rust1", since = "1.0.0")]
    1914    pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
    1915        self._open(path.as_ref())
    1916    }
    1917
    1918    fn _open(&self, path: &Path) -> io::Result<File> {
    1919        fs_imp::File::open(path, &self.0).map(|inner| File { inner })
    1920    }
    1921}
    1922
    1923impl AsInner<fs_imp::OpenOptions> for OpenOptions {
    1924    #[inline]
    1925    fn as_inner(&self) -> &fs_imp::OpenOptions {
    1926        &self.0
    1927    }
    1928}
    1929
    1930impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
    1931    #[inline]
    1932    fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
    1933        &mut self.0
    1934    }
    1935}
    1936
    1937impl Metadata {
    1938    /// Returns the file type for this metadata.
    1939    ///
    1940    /// # Examples
    1941    ///
    1942    /// ```no_run
    1943    /// fn main() -> std::io::Result<()> {
    1944    ///     use std::fs;
    1945    ///
    1946    ///     let metadata = fs::metadata("foo.txt")?;
    1947    ///
    1948    ///     println!("{:?}", metadata.file_type());
    1949    ///     Ok(())
    1950    /// }
    1951    /// ```
    1952    #[must_use]
    1953    #[stable(feature = "file_type", since = "1.1.0")]
    1954    pub fn file_type(&self) -> FileType {
    1955        FileType(self.0.file_type())
    1956    }
    1957
    1958    /// Returns `true` if this metadata is for a directory. The
    1959    /// result is mutually exclusive to the result of
    1960    /// [`Metadata::is_file`], and will be false for symlink metadata
    1961    /// obtained from [`symlink_metadata`].
    1962    ///
    1963    /// # Examples
    1964    ///
    1965    /// ```no_run
    1966    /// fn main() -> std::io::Result<()> {
    1967    ///     use std::fs;
    1968    ///
    1969    ///     let metadata = fs::metadata("foo.txt")?;
    1970    ///
    1971    ///     assert!(!metadata.is_dir());
    1972    ///     Ok(())
    1973    /// }
    1974    /// ```
    1975    #[must_use]
    1976    #[stable(feature = "rust1", since = "1.0.0")]
    1977    pub fn is_dir(&self) -> bool {
    1978        self.file_type().is_dir()
    1979    }
    1980
    1981    /// Returns `true` if this metadata is for a regular file. The
    1982    /// result is mutually exclusive to the result of
    1983    /// [`Metadata::is_dir`], and will be false for symlink metadata
    1984    /// obtained from [`symlink_metadata`].
    1985    ///
    1986    /// When the goal is simply to read from (or write to) the source, the most
    1987    /// reliable way to test the source can be read (or written to) is to open
    1988    /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
    1989    /// a Unix-like system for example. See [`File::open`] or
    1990    /// [`OpenOptions::open`] for more information.
    1991    ///
    1992    /// # Examples
    1993    ///
    1994    /// ```no_run
    1995    /// use std::fs;
    1996    ///
    1997    /// fn main() -> std::io::Result<()> {
    1998    ///     let metadata = fs::metadata("foo.txt")?;
    1999    ///
    2000    ///     assert!(metadata.is_file());
    2001    ///     Ok(())
    2002    /// }
    2003    /// ```
    2004    #[must_use]
    2005    #[stable(feature = "rust1", since = "1.0.0")]
    2006    pub fn is_file(&self) -> bool {
    2007        self.file_type().is_file()
    2008    }
    2009
    2010    /// Returns `true` if this metadata is for a symbolic link.
    2011    ///
    2012    /// # Examples
    2013    ///
    2014    #[cfg_attr(unix, doc = "```no_run")]
    2015    #[cfg_attr(not(unix), doc = "```ignore")]
    2016    /// use std::fs;
    2017    /// use std::path::Path;
    2018    /// use std::os::unix::fs::symlink;
    2019    ///
    2020    /// fn main() -> std::io::Result<()> {
    2021    ///     let link_path = Path::new("link");
    2022    ///     symlink("/origin_does_not_exist/", link_path)?;
    2023    ///
    2024    ///     let metadata = fs::symlink_metadata(link_path)?;
    2025    ///
    2026    ///     assert!(metadata.is_symlink());
    2027    ///     Ok(())
    2028    /// }
    2029    /// ```
    2030    #[must_use]
    2031    #[stable(feature = "is_symlink", since = "1.58.0")]
    2032    pub fn is_symlink(&self) -> bool {
    2033        self.file_type().is_symlink()
    2034    }
    2035
    2036    /// Returns the size of the file, in bytes, this metadata is for.
    2037    ///
    2038    /// # Examples
    2039    ///
    2040    /// ```no_run
    2041    /// use std::fs;
    2042    ///
    2043    /// fn main() -> std::io::Result<()> {
    2044    ///     let metadata = fs::metadata("foo.txt")?;
    2045    ///
    2046    ///     assert_eq!(0, metadata.len());
    2047    ///     Ok(())
    2048    /// }
    2049    /// ```
    2050    #[must_use]
    2051    #[stable(feature = "rust1", since = "1.0.0")]
    2052    pub fn len(&self) -> u64 {
    2053        self.0.size()
    2054    }
    2055
    2056    /// Returns the permissions of the file this metadata is for.
    2057    ///
    2058    /// # Examples
    2059    ///
    2060    /// ```no_run
    2061    /// use std::fs;
    2062    ///
    2063    /// fn main() -> std::io::Result<()> {
    2064    ///     let metadata = fs::metadata("foo.txt")?;
    2065    ///
    2066    ///     assert!(!metadata.permissions().readonly());
    2067    ///     Ok(())
    2068    /// }
    2069    /// ```
    2070    #[must_use]
    2071    #[stable(feature = "rust1", since = "1.0.0")]
    2072    pub fn permissions(&self) -> Permissions {
    2073        Permissions(self.0.perm())
    2074    }
    2075
    2076    /// Returns the last modification time listed in this metadata.
    2077    ///
    2078    /// The returned value corresponds to the `mtime` field of `stat` on Unix
    2079    /// platforms and the `ftLastWriteTime` field on Windows platforms.
    2080    ///
    2081    /// # Errors
    2082    ///
    2083    /// This field might not be available on all platforms, and will return an
    2084    /// `Err` on platforms where it is not available.
    2085    ///
    2086    /// # Examples
    2087    ///
    2088    /// ```no_run
    2089    /// use std::fs;
    2090    ///
    2091    /// fn main() -> std::io::Result<()> {
    2092    ///     let metadata = fs::metadata("foo.txt")?;
    2093    ///
    2094    ///     if let Ok(time) = metadata.modified() {
    2095    ///         println!("{time:?}");
    2096    ///     } else {
    2097    ///         println!("Not supported on this platform");
    2098    ///     }
    2099    ///     Ok(())
    2100    /// }
    2101    /// ```
    2102    #[doc(alias = "mtime", alias = "ftLastWriteTime")]
    2103    #[stable(feature = "fs_time", since = "1.10.0")]
    2104    pub fn modified(&self) -> io::Result<SystemTime> {
    2105        self.0.modified().map(FromInner::from_inner)
    2106    }
    2107
    2108    /// Returns the last access time of this metadata.
    2109    ///
    2110    /// The returned value corresponds to the `atime` field of `stat` on Unix
    2111    /// platforms and the `ftLastAccessTime` field on Windows platforms.
    2112    ///
    2113    /// Note that not all platforms will keep this field update in a file's
    2114    /// metadata, for example Windows has an option to disable updating this
    2115    /// time when files are accessed and Linux similarly has `noatime`.
    2116    ///
    2117    /// # Errors
    2118    ///
    2119    /// This field might not be available on all platforms, and will return an
    2120    /// `Err` on platforms where it is not available.
    2121    ///
    2122    /// # Examples
    2123    ///
    2124    /// ```no_run
    2125    /// use std::fs;
    2126    ///
    2127    /// fn main() -> std::io::Result<()> {
    2128    ///     let metadata = fs::metadata("foo.txt")?;
    2129    ///
    2130    ///     if let Ok(time) = metadata.accessed() {
    2131    ///         println!("{time:?}");
    2132    ///     } else {
    2133    ///         println!("Not supported on this platform");
    2134    ///     }
    2135    ///     Ok(())
    2136    /// }
    2137    /// ```
    2138    #[doc(alias = "atime", alias = "ftLastAccessTime")]
    2139    #[stable(feature = "fs_time", since = "1.10.0")]
    2140    pub fn accessed(&self) -> io::Result<SystemTime> {
    2141        self.0.accessed().map(FromInner::from_inner)
    2142    }
    2143
    2144    /// Returns the creation time listed in this metadata.
    2145    ///
    2146    /// The returned value corresponds to the `btime` field of `statx` on
    2147    /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
    2148    /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
    2149    ///
    2150    /// # Errors
    2151    ///
    2152    /// This field might not be available on all platforms, and will return an
    2153    /// `Err` on platforms or filesystems where it is not available.
    2154    ///
    2155    /// # Examples
    2156    ///
    2157    /// ```no_run
    2158    /// use std::fs;
    2159    ///
    2160    /// fn main() -> std::io::Result<()> {
    2161    ///     let metadata = fs::metadata("foo.txt")?;
    2162    ///
    2163    ///     if let Ok(time) = metadata.created() {
    2164    ///         println!("{time:?}");
    2165    ///     } else {
    2166    ///         println!("Not supported on this platform or filesystem");
    2167    ///     }
    2168    ///     Ok(())
    2169    /// }
    2170    /// ```
    2171    #[doc(alias = "btime", alias = "birthtime", alias = "ftCreationTime")]
    2172    #[stable(feature = "fs_time", since = "1.10.0")]
    2173    pub fn created(&self) -> io::Result<SystemTime> {
    2174        self.0.created().map(FromInner::from_inner)
    2175    }
    2176}
    2177
    2178#[stable(feature = "std_debug", since = "1.16.0")]
    2179impl fmt::Debug for Metadata {
    2180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    2181        let mut debug = f.debug_struct("Metadata");
    2182        debug.field("file_type", &self.file_type());
    2183        debug.field("permissions", &self.permissions());
    2184        debug.field("len", &self.len());
    2185        if let Ok(modified) = self.modified() {
    2186            debug.field("modified", &modified);
    2187        }
    2188        if let Ok(accessed) = self.accessed() {
    2189            debug.field("accessed", &accessed);
    2190        }
    2191        if let Ok(created) = self.created() {
    2192            debug.field("created", &created);
    2193        }
    2194        debug.finish_non_exhaustive()
    2195    }
    2196}
    2197
    2198impl AsInner<fs_imp::FileAttr> for Metadata {
    2199    #[inline]
    2200    fn as_inner(&self) -> &fs_imp::FileAttr {
    2201        &self.0
    2202    }
    2203}
    2204
    2205impl FromInner<fs_imp::FileAttr> for Metadata {
    2206    fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
    2207        Metadata(attr)
    2208    }
    2209}
    2210
    2211impl FileTimes {
    2212    /// Creates a new `FileTimes` with no times set.
    2213    ///
    2214    /// Using the resulting `FileTimes` in [`File::set_times`] will not modify any timestamps.
    2215    #[stable(feature = "file_set_times", since = "1.75.0")]
    2216    pub fn new() -> Self {
    2217        Self::default()
    2218    }
    2219
    2220    /// Set the last access time of a file.
    2221    #[stable(feature = "file_set_times", since = "1.75.0")]
    2222    pub fn set_accessed(mut self, t: SystemTime) -> Self {
    2223        self.0.set_accessed(t.into_inner());
    2224        self
    2225    }
    2226
    2227    /// Set the last modified time of a file.
    2228    #[stable(feature = "file_set_times", since = "1.75.0")]
    2229    pub fn set_modified(mut self, t: SystemTime) -> Self {
    2230        self.0.set_modified(t.into_inner());
    2231        self
    2232    }
    2233}
    2234
    2235impl AsInnerMut<fs_imp::FileTimes> for FileTimes {
    2236    fn as_inner_mut(&mut self) -> &mut fs_imp::FileTimes {
    2237        &mut self.0
    2238    }
    2239}
    2240
    2241// For implementing OS extension traits in `std::os`
    2242#[stable(feature = "file_set_times", since = "1.75.0")]
    2243impl Sealed for FileTimes {}
    2244
    2245impl Permissions {
    2246    /// Returns `true` if these permissions describe a readonly (unwritable) file.
    2247    ///
    2248    /// # Note
    2249    ///
    2250    /// This function does not take Access Control Lists (ACLs), Unix group
    2251    /// membership and other nuances into account.
    2252    /// Therefore the return value of this function cannot be relied upon
    2253    /// to predict whether attempts to read or write the file will actually succeed.
    2254    ///
    2255    /// # Windows
    2256    ///
    2257    /// On Windows this returns [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
    2258    /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
    2259    /// but the user may still have permission to change this flag. If
    2260    /// `FILE_ATTRIBUTE_READONLY` is *not* set then writes may still fail due
    2261    /// to lack of write permission.
    2262    /// The behavior of this attribute for directories depends on the Windows
    2263    /// version.
    2264    ///
    2265    /// # Unix (including macOS)
    2266    ///
    2267    /// On Unix-based platforms this checks if *any* of the owner, group or others
    2268    /// write permission bits are set. It does not consider anything else, including:
    2269    ///
    2270    /// * Whether the current user is in the file's assigned group.
    2271    /// * Permissions granted by ACL.
    2272    /// * That `root` user can write to files that do not have any write bits set.
    2273    /// * Writable files on a filesystem that is mounted read-only.
    2274    ///
    2275    /// The [`PermissionsExt`] trait gives direct access to the permission bits but
    2276    /// also does not read ACLs.
    2277    ///
    2278    /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
    2279    ///
    2280    /// # Examples
    2281    ///
    2282    /// ```no_run
    2283    /// use std::fs::File;
    2284    ///
    2285    /// fn main() -> std::io::Result<()> {
    2286    ///     let mut f = File::create("foo.txt")?;
    2287    ///     let metadata = f.metadata()?;
    2288    ///
    2289    ///     assert_eq!(false, metadata.permissions().readonly());
    2290    ///     Ok(())
    2291    /// }
    2292    /// ```
    2293    #[must_use = "call `set_readonly` to modify the readonly flag"]
    2294    #[stable(feature = "rust1", since = "1.0.0")]
    2295    pub fn readonly(&self) -> bool {
    2296        self.0.readonly()
    2297    }
    2298
    2299    /// Modifies the readonly flag for this set of permissions. If the
    2300    /// `readonly` argument is `true`, using the resulting `Permission` will
    2301    /// update file permissions to forbid writing. Conversely, if it's `false`,
    2302    /// using the resulting `Permission` will update file permissions to allow
    2303    /// writing.
    2304    ///
    2305    /// This operation does **not** modify the files attributes. This only
    2306    /// changes the in-memory value of these attributes for this `Permissions`
    2307    /// instance. To modify the files attributes use the [`set_permissions`]
    2308    /// function which commits these attribute changes to the file.
    2309    ///
    2310    /// # Note
    2311    ///
    2312    /// `set_readonly(false)` makes the file *world-writable* on Unix.
    2313    /// You can use the [`PermissionsExt`] trait on Unix to avoid this issue.
    2314    ///
    2315    /// It also does not take Access Control Lists (ACLs) or Unix group
    2316    /// membership into account.
    2317    ///
    2318    /// # Windows
    2319    ///
    2320    /// On Windows this sets or clears [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
    2321    /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
    2322    /// but the user may still have permission to change this flag. If
    2323    /// `FILE_ATTRIBUTE_READONLY` is *not* set then the write may still fail if
    2324    /// the user does not have permission to write to the file.
    2325    ///
    2326    /// In Windows 7 and earlier this attribute prevents deleting empty
    2327    /// directories. It does not prevent modifying the directory contents.
    2328    /// On later versions of Windows this attribute is ignored for directories.
    2329    ///
    2330    /// # Unix (including macOS)
    2331    ///
    2332    /// On Unix-based platforms this sets or clears the write access bit for
    2333    /// the owner, group *and* others, equivalent to `chmod a+w <file>`
    2334    /// or `chmod a-w <file>` respectively. The latter will grant write access
    2335    /// to all users! You can use the [`PermissionsExt`] trait on Unix
    2336    /// to avoid this issue.
    2337    ///
    2338    /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
    2339    ///
    2340    /// # Examples
    2341    ///
    2342    /// ```no_run
    2343    /// use std::fs::File;
    2344    ///
    2345    /// fn main() -> std::io::Result<()> {
    2346    ///     let f = File::create("foo.txt")?;
    2347    ///     let metadata = f.metadata()?;
    2348    ///     let mut permissions = metadata.permissions();
    2349    ///
    2350    ///     permissions.set_readonly(true);
    2351    ///
    2352    ///     // filesystem doesn't change, only the in memory state of the
    2353    ///     // readonly permission
    2354    ///     assert_eq!(false, metadata.permissions().readonly());
    2355    ///
    2356    ///     // just this particular `permissions`.
    2357    ///     assert_eq!(true, permissions.readonly());
    2358    ///     Ok(())
    2359    /// }
    2360    /// ```
    2361    #[stable(feature = "rust1", since = "1.0.0")]
    2362    pub fn set_readonly(&mut self, readonly: bool) {
    2363        self.0.set_readonly(readonly)
    2364    }
    2365}
    2366
    2367impl FileType {
    2368    /// Tests whether this file type represents a directory. The
    2369    /// result is mutually exclusive to the results of
    2370    /// [`is_file`] and [`is_symlink`]; only zero or one of these
    2371    /// tests may pass.
    2372    ///
    2373    /// [`is_file`]: FileType::is_file
    2374    /// [`is_symlink`]: FileType::is_symlink
    2375    ///
    2376    /// # Examples
    2377    ///
    2378    /// ```no_run
    2379    /// fn main() -> std::io::Result<()> {
    2380    ///     use std::fs;
    2381    ///
    2382    ///     let metadata = fs::metadata("foo.txt")?;
    2383    ///     let file_type = metadata.file_type();
    2384    ///
    2385    ///     assert_eq!(file_type.is_dir(), false);
    2386    ///     Ok(())
    2387    /// }
    2388    /// ```
    2389    #[must_use]
    2390    #[stable(feature = "file_type", since = "1.1.0")]
    2391    pub fn is_dir(&self) -> bool {
    2392        self.0.is_dir()
    2393    }
    2394
    2395    /// Tests whether this file type represents a regular file.
    2396    /// The result is mutually exclusive to the results of
    2397    /// [`is_dir`] and [`is_symlink`]; only zero or one of these
    2398    /// tests may pass.
    2399    ///
    2400    /// When the goal is simply to read from (or write to) the source, the most
    2401    /// reliable way to test the source can be read (or written to) is to open
    2402    /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
    2403    /// a Unix-like system for example. See [`File::open`] or
    2404    /// [`OpenOptions::open`] for more information.
    2405    ///
    2406    /// [`is_dir`]: FileType::is_dir
    2407    /// [`is_symlink`]: FileType::is_symlink
    2408    ///
    2409    /// # Examples
    2410    ///
    2411    /// ```no_run
    2412    /// fn main() -> std::io::Result<()> {
    2413    ///     use std::fs;
    2414    ///
    2415    ///     let metadata = fs::metadata("foo.txt")?;
    2416    ///     let file_type = metadata.file_type();
    2417    ///
    2418    ///     assert_eq!(file_type.is_file(), true);
    2419    ///     Ok(())
    2420    /// }
    2421    /// ```
    2422    #[must_use]
    2423    #[stable(feature = "file_type", since = "1.1.0")]
    2424    pub fn is_file(&self) -> bool {
    2425        self.0.is_file()
    2426    }
    2427
    2428    /// Tests whether this file type represents a symbolic link.
    2429    /// The result is mutually exclusive to the results of
    2430    /// [`is_dir`] and [`is_file`]; only zero or one of these
    2431    /// tests may pass.
    2432    ///
    2433    /// The underlying [`Metadata`] struct needs to be retrieved
    2434    /// with the [`fs::symlink_metadata`] function and not the
    2435    /// [`fs::metadata`] function. The [`fs::metadata`] function
    2436    /// follows symbolic links, so [`is_symlink`] would always
    2437    /// return `false` for the target file.
    2438    ///
    2439    /// [`fs::metadata`]: metadata
    2440    /// [`fs::symlink_metadata`]: symlink_metadata
    2441    /// [`is_dir`]: FileType::is_dir
    2442    /// [`is_file`]: FileType::is_file
    2443    /// [`is_symlink`]: FileType::is_symlink
    2444    ///
    2445    /// # Examples
    2446    ///
    2447    /// ```no_run
    2448    /// use std::fs;
    2449    ///
    2450    /// fn main() -> std::io::Result<()> {
    2451    ///     let metadata = fs::symlink_metadata("foo.txt")?;
    2452    ///     let file_type = metadata.file_type();
    2453    ///
    2454    ///     assert_eq!(file_type.is_symlink(), false);
    2455    ///     Ok(())
    2456    /// }
    2457    /// ```
    2458    #[must_use]
    2459    #[stable(feature = "file_type", since = "1.1.0")]
    2460    pub fn is_symlink(&self) -> bool {
    2461        self.0.is_symlink()
    2462    }
    2463}
    2464
    2465#[stable(feature = "std_debug", since = "1.16.0")]
    2466impl fmt::Debug for FileType {
    2467    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    2468        f.debug_struct("FileType")
    2469            .field("is_file", &self.is_file())
    2470            .field("is_dir", &self.is_dir())
    2471            .field("is_symlink", &self.is_symlink())
    2472            .finish_non_exhaustive()
    2473    }
    2474}
    2475
    2476impl AsInner<fs_imp::FileType> for FileType {
    2477    #[inline]
    2478    fn as_inner(&self) -> &fs_imp::FileType {
    2479        &self.0
    2480    }
    2481}
    2482
    2483impl FromInner<fs_imp::FilePermissions> for Permissions {
    2484    fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
    2485        Permissions(f)
    2486    }
    2487}
    2488
    2489impl AsInner<fs_imp::FilePermissions> for Permissions {
    2490    #[inline]
    2491    fn as_inner(&self) -> &fs_imp::FilePermissions {
    2492        &self.0
    2493    }
    2494}
    2495
    2496#[stable(feature = "rust1", since = "1.0.0")]
    2497impl Iterator for ReadDir {
    2498    type Item = io::Result<DirEntry>;
    2499
    2500    fn next(&mut self) -> Option<io::Result<DirEntry>> {
    2501        self.0.next().map(|entry| entry.map(DirEntry))
    2502    }
    2503}
    2504
    2505impl DirEntry {
    2506    /// Returns the full path to the file that this entry represents.
    2507    ///
    2508    /// The full path is created by joining the original path to `read_dir`
    2509    /// with the filename of this entry.
    2510    ///
    2511    /// # Examples
    2512    ///
    2513    /// ```no_run
    2514    /// use std::fs;
    2515    ///
    2516    /// fn main() -> std::io::Result<()> {
    2517    ///     for entry in fs::read_dir(".")? {
    2518    ///         let dir = entry?;
    2519    ///         println!("{:?}", dir.path());
    2520    ///     }
    2521    ///     Ok(())
    2522    /// }
    2523    /// ```
    2524    ///
    2525    /// This prints output like:
    2526    ///
    2527    /// ```text
    2528    /// "./whatever.txt"
    2529    /// "./foo.html"
    2530    /// "./hello_world.rs"
    2531    /// ```
    2532    ///
    2533    /// The exact text, of course, depends on what files you have in `.`.
    2534    #[must_use]
    2535    #[stable(feature = "rust1", since = "1.0.0")]
    2536    pub fn path(&self) -> PathBuf {
    2537        self.0.path()
    2538    }
    2539
    2540    /// Returns the metadata for the file that this entry points at.
    2541    ///
    2542    /// This function will not traverse symlinks if this entry points at a
    2543    /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
    2544    ///
    2545    /// [`fs::metadata`]: metadata
    2546    /// [`fs::File::metadata`]: File::metadata
    2547    ///
    2548    /// # Platform-specific behavior
    2549    ///
    2550    /// On Windows this function is cheap to call (no extra system calls
    2551    /// needed), but on Unix platforms this function is the equivalent of
    2552    /// calling `symlink_metadata` on the path.
    2553    ///
    2554    /// # Examples
    2555    ///
    2556    /// ```
    2557    /// use std::fs;
    2558    ///
    2559    /// if let Ok(entries) = fs::read_dir(".") {
    2560    ///     for entry in entries {
    2561    ///         if let Ok(entry) = entry {
    2562    ///             // Here, `entry` is a `DirEntry`.
    2563    ///             if let Ok(metadata) = entry.metadata() {
    2564    ///                 // Now let's show our entry's permissions!
    2565    ///                 println!("{:?}: {:?}", entry.path(), metadata.permissions());
    2566    ///             } else {
    2567    ///                 println!("Couldn't get metadata for {:?}", entry.path());
    2568    ///             }
    2569    ///         }
    2570    ///     }
    2571    /// }
    2572    /// ```
    2573    #[stable(feature = "dir_entry_ext", since = "1.1.0")]
    2574    pub fn metadata(&self) -> io::Result<Metadata> {
    2575        self.0.metadata().map(Metadata)
    2576    }
    2577
    2578    /// Returns the file type for the file that this entry points at.
    2579    ///
    2580    /// This function will not traverse symlinks if this entry points at a
    2581    /// symlink.
    2582    ///
    2583    /// # Platform-specific behavior
    2584    ///
    2585    /// On Windows and most Unix platforms this function is free (no extra
    2586    /// system calls needed), but some Unix platforms may require the equivalent
    2587    /// call to `symlink_metadata` to learn about the target file type.
    2588    ///
    2589    /// # Examples
    2590    ///
    2591    /// ```
    2592    /// use std::fs;
    2593    ///
    2594    /// if let Ok(entries) = fs::read_dir(".") {
    2595    ///     for entry in entries {
    2596    ///         if let Ok(entry) = entry {
    2597    ///             // Here, `entry` is a `DirEntry`.
    2598    ///             if let Ok(file_type) = entry.file_type() {
    2599    ///                 // Now let's show our entry's file type!
    2600    ///                 println!("{:?}: {:?}", entry.path(), file_type);
    2601    ///             } else {
    2602    ///                 println!("Couldn't get file type for {:?}", entry.path());
    2603    ///             }
    2604    ///         }
    2605    ///     }
    2606    /// }
    2607    /// ```
    2608    #[stable(feature = "dir_entry_ext", since = "1.1.0")]
    2609    pub fn file_type(&self) -> io::Result<FileType> {
    2610        self.0.file_type().map(FileType)
    2611    }
    2612
    2613    /// Returns the file name of this directory entry without any
    2614    /// leading path component(s).
    2615    ///
    2616    /// As an example,
    2617    /// the output of the function will result in "foo" for all the following paths:
    2618    /// - "./foo"
    2619    /// - "/the/foo"
    2620    /// - "../../foo"
    2621    ///
    2622    /// # Examples
    2623    ///
    2624    /// ```
    2625    /// use std::fs;
    2626    ///
    2627    /// if let Ok(entries) = fs::read_dir(".") {
    2628    ///     for entry in entries {
    2629    ///         if let Ok(entry) = entry {
    2630    ///             // Here, `entry` is a `DirEntry`.
    2631    ///             println!("{:?}", entry.file_name());
    2632    ///         }
    2633    ///     }
    2634    /// }
    2635    /// ```
    2636    #[must_use]
    2637    #[stable(feature = "dir_entry_ext", since = "1.1.0")]
    2638    pub fn file_name(&self) -> OsString {
    2639        self.0.file_name()
    2640    }
    2641}
    2642
    2643#[stable(feature = "dir_entry_debug", since = "1.13.0")]
    2644impl fmt::Debug for DirEntry {
    2645    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    2646        f.debug_tuple("DirEntry").field(&self.path()).finish()
    2647    }
    2648}
    2649
    2650impl AsInner<fs_imp::DirEntry> for DirEntry {
    2651    #[inline]
    2652    fn as_inner(&self) -> &fs_imp::DirEntry {
    2653        &self.0
    2654    }
    2655}
    2656
    2657/// Removes a file from the filesystem.
    2658///
    2659/// Note that there is no
    2660/// guarantee that the file is immediately deleted (e.g., depending on
    2661/// platform, other open file descriptors may prevent immediate removal).
    2662///
    2663/// # Platform-specific behavior
    2664///
    2665/// This function currently corresponds to the `unlink` function on Unix.
    2666/// On Windows, `DeleteFile` is used or `CreateFileW` and `SetInformationByHandle` for readonly files.
    2667/// Note that, this [may change in the future][changes].
    2668///
    2669/// [changes]: io#platform-specific-behavior
    2670///
    2671/// # Errors
    2672///
    2673/// This function will return an error in the following situations, but is not
    2674/// limited to just these cases:
    2675///
    2676/// * `path` points to a directory.
    2677/// * The file doesn't exist.
    2678/// * The user lacks permissions to remove the file.
    2679///
    2680/// This function will only ever return an error of kind `NotFound` if the given
    2681/// path does not exist. Note that the inverse is not true,
    2682/// ie. if a path does not exist, its removal may fail for a number of reasons,
    2683/// such as insufficient permissions.
    2684///
    2685/// # Examples
    2686///
    2687/// ```no_run
    2688/// use std::fs;
    2689///
    2690/// fn main() -> std::io::Result<()> {
    2691///     fs::remove_file("a.txt")?;
    2692///     Ok(())
    2693/// }
    2694/// ```
    2695#[doc(alias = "rm", alias = "unlink", alias = "DeleteFile")]
    2696#[stable(feature = "rust1", since = "1.0.0")]
    2697pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
    2698    fs_imp::remove_file(path.as_ref())
    2699}
    2700
    2701/// Given a path, queries the file system to get information about a file,
    2702/// directory, etc.
    2703///
    2704/// This function will traverse symbolic links to query information about the
    2705/// destination file.
    2706///
    2707/// # Platform-specific behavior
    2708///
    2709/// This function currently corresponds to the `stat` function on Unix
    2710/// and the `GetFileInformationByHandle` function on Windows.
    2711/// Note that, this [may change in the future][changes].
    2712///
    2713/// [changes]: io#platform-specific-behavior
    2714///
    2715/// # Errors
    2716///
    2717/// This function will return an error in the following situations, but is not
    2718/// limited to just these cases:
    2719///
    2720/// * The user lacks permissions to perform `metadata` call on `path`.
    2721/// * `path` does not exist.
    2722///
    2723/// # Examples
    2724///
    2725/// ```rust,no_run
    2726/// use std::fs;
    2727///
    2728/// fn main() -> std::io::Result<()> {
    2729///     let attr = fs::metadata("/some/file/path.txt")?;
    2730///     // inspect attr ...
    2731///     Ok(())
    2732/// }
    2733/// ```
    2734#[doc(alias = "stat")]
    2735#[stable(feature = "rust1", since = "1.0.0")]
    2736pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
    2737    fs_imp::metadata(path.as_ref()).map(Metadata)
    2738}
    2739
    2740/// Queries the metadata about a file without following symlinks.
    2741///
    2742/// # Platform-specific behavior
    2743///
    2744/// This function currently corresponds to the `lstat` function on Unix
    2745/// and the `GetFileInformationByHandle` function on Windows.
    2746/// Note that, this [may change in the future][changes].
    2747///
    2748/// [changes]: io#platform-specific-behavior
    2749///
    2750/// # Errors
    2751///
    2752/// This function will return an error in the following situations, but is not
    2753/// limited to just these cases:
    2754///
    2755/// * The user lacks permissions to perform `metadata` call on `path`.
    2756/// * `path` does not exist.
    2757///
    2758/// # Examples
    2759///
    2760/// ```rust,no_run
    2761/// use std::fs;
    2762///
    2763/// fn main() -> std::io::Result<()> {
    2764///     let attr = fs::symlink_metadata("/some/file/path.txt")?;
    2765///     // inspect attr ...
    2766///     Ok(())
    2767/// }
    2768/// ```
    2769#[doc(alias = "lstat")]
    2770#[stable(feature = "symlink_metadata", since = "1.1.0")]
    2771pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
    2772    fs_imp::symlink_metadata(path.as_ref()).map(Metadata)
    2773}
    2774
    2775/// Renames a file or directory to a new name, replacing the original file if
    2776/// `to` already exists.
    2777///
    2778/// This will not work if the new name is on a different mount point.
    2779///
    2780/// # Platform-specific behavior
    2781///
    2782/// This function currently corresponds to the `rename` function on Unix
    2783/// and the `MoveFileExW` or `SetFileInformationByHandle` function on Windows.
    2784///
    2785/// Because of this, the behavior when both `from` and `to` exist differs. On
    2786/// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
    2787/// `from` is not a directory, `to` must also be not a directory. The behavior
    2788/// on Windows is the same on Windows 10 1607 and higher if `FileRenameInfoEx`
    2789/// is supported by the filesystem; otherwise, `from` can be anything, but
    2790/// `to` must *not* be a directory.
    2791///
    2792/// Note that, this [may change in the future][changes].
    2793///
    2794/// [changes]: io#platform-specific-behavior
    2795///
    2796/// # Errors
    2797///
    2798/// This function will return an error in the following situations, but is not
    2799/// limited to just these cases:
    2800///
    2801/// * `from` does not exist.
    2802/// * The user lacks permissions to view contents.
    2803/// * `from` and `to` are on separate filesystems.
    2804///
    2805/// # Examples
    2806///
    2807/// ```no_run
    2808/// use std::fs;
    2809///
    2810/// fn main() -> std::io::Result<()> {
    2811///     fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
    2812///     Ok(())
    2813/// }
    2814/// ```
    2815#[doc(alias = "mv", alias = "MoveFile", alias = "MoveFileEx")]
    2816#[stable(feature = "rust1", since = "1.0.0")]
    2817pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
    2818    fs_imp::rename(from.as_ref(), to.as_ref())
    2819}
    2820
    2821/// Copies the contents of one file to another. This function will also
    2822/// copy the permission bits of the original file to the destination file.
    2823///
    2824/// This function will **overwrite** the contents of `to`.
    2825///
    2826/// Note that if `from` and `to` both point to the same file, then the file
    2827/// will likely get truncated by this operation.
    2828///
    2829/// On success, the total number of bytes copied is returned and it is equal to
    2830/// the length of the `to` file as reported by `metadata`.
    2831///
    2832/// If you want to copy the contents of one file to another and you’re
    2833/// working with [`File`]s, see the [`io::copy`](io::copy()) function.
    2834///
    2835/// # Platform-specific behavior
    2836///
    2837/// This function currently corresponds to the `open` function in Unix
    2838/// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
    2839/// `O_CLOEXEC` is set for returned file descriptors.
    2840///
    2841/// On Linux (including Android), this function attempts to use `copy_file_range(2)`,
    2842/// and falls back to reading and writing if that is not possible.
    2843///
    2844/// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
    2845/// NTFS streams are copied but only the size of the main stream is returned by
    2846/// this function.
    2847///
    2848/// On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`.
    2849///
    2850/// Note that platform-specific behavior [may change in the future][changes].
    2851///
    2852/// [changes]: io#platform-specific-behavior
    2853///
    2854/// # Errors
    2855///
    2856/// This function will return an error in the following situations, but is not
    2857/// limited to just these cases:
    2858///
    2859/// * `from` is neither a regular file nor a symlink to a regular file.
    2860/// * `from` does not exist.
    2861/// * The current process does not have the permission rights to read
    2862///   `from` or write `to`.
    2863/// * The parent directory of `to` doesn't exist.
    2864///
    2865/// # Examples
    2866///
    2867/// ```no_run
    2868/// use std::fs;
    2869///
    2870/// fn main() -> std::io::Result<()> {
    2871///     fs::copy("foo.txt", "bar.txt")?;  // Copy foo.txt to bar.txt
    2872///     Ok(())
    2873/// }
    2874/// ```
    2875#[doc(alias = "cp")]
    2876#[doc(alias = "CopyFile", alias = "CopyFileEx")]
    2877#[doc(alias = "fclonefileat", alias = "fcopyfile")]
    2878#[stable(feature = "rust1", since = "1.0.0")]
    2879pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
    2880    fs_imp::copy(from.as_ref(), to.as_ref())
    2881}
    2882
    2883/// Creates a new hard link on the filesystem.
    2884///
    2885/// The `link` path will be a link pointing to the `original` path. Note that
    2886/// systems often require these two paths to both be located on the same
    2887/// filesystem.
    2888///
    2889/// If `original` names a symbolic link, it is platform-specific whether the
    2890/// symbolic link is followed. On platforms where it's possible to not follow
    2891/// it, it is not followed, and the created hard link points to the symbolic
    2892/// link itself.
    2893///
    2894/// # Platform-specific behavior
    2895///
    2896/// This function currently corresponds the `CreateHardLink` function on Windows.
    2897/// On most Unix systems, it corresponds to the `linkat` function with no flags.
    2898/// On Android, VxWorks, and Redox, it instead corresponds to the `link` function.
    2899/// On MacOS, it uses the `linkat` function if it is available, but on very old
    2900/// systems where `linkat` is not available, `link` is selected at runtime instead.
    2901/// Note that, this [may change in the future][changes].
    2902///
    2903/// [changes]: io#platform-specific-behavior
    2904///
    2905/// # Errors
    2906///
    2907/// This function will return an error in the following situations, but is not
    2908/// limited to just these cases:
    2909///
    2910/// * The `original` path is not a file or doesn't exist.
    2911/// * The 'link' path already exists.
    2912///
    2913/// # Examples
    2914///
    2915/// ```no_run
    2916/// use std::fs;
    2917///
    2918/// fn main() -> std::io::Result<()> {
    2919///     fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
    2920///     Ok(())
    2921/// }
    2922/// ```
    2923#[doc(alias = "CreateHardLink", alias = "linkat")]
    2924#[stable(feature = "rust1", since = "1.0.0")]
    2925pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
    2926    fs_imp::hard_link(original.as_ref(), link.as_ref())
    2927}
    2928
    2929/// Creates a new symbolic link on the filesystem.
    2930///
    2931/// The `link` path will be a symbolic link pointing to the `original` path.
    2932/// On Windows, this will be a file symlink, not a directory symlink;
    2933/// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
    2934/// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
    2935/// used instead to make the intent explicit.
    2936///
    2937/// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
    2938/// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
    2939/// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
    2940///
    2941/// # Examples
    2942///
    2943/// ```no_run
    2944/// use std::fs;
    2945///
    2946/// fn main() -> std::io::Result<()> {
    2947///     fs::soft_link("a.txt", "b.txt")?;
    2948///     Ok(())
    2949/// }
    2950/// ```
    2951#[stable(feature = "rust1", since = "1.0.0")]
    2952#[deprecated(
    2953    since = "1.1.0",
    2954    note = "replaced with std::os::unix::fs::symlink and \
    2955            std::os::windows::fs::{symlink_file, symlink_dir}"
    2956)]
    2957pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
    2958    fs_imp::symlink(original.as_ref(), link.as_ref())
    2959}
    2960
    2961/// Reads a symbolic link, returning the file that the link points to.
    2962///
    2963/// # Platform-specific behavior
    2964///
    2965/// This function currently corresponds to the `readlink` function on Unix
    2966/// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
    2967/// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
    2968/// Note that, this [may change in the future][changes].
    2969///
    2970/// [changes]: io#platform-specific-behavior
    2971///
    2972/// # Errors
    2973///
    2974/// This function will return an error in the following situations, but is not
    2975/// limited to just these cases:
    2976///
    2977/// * `path` is not a symbolic link.
    2978/// * `path` does not exist.
    2979///
    2980/// # Examples
    2981///
    2982/// ```no_run
    2983/// use std::fs;
    2984///
    2985/// fn main() -> std::io::Result<()> {
    2986///     let path = fs::read_link("a.txt")?;
    2987///     Ok(())
    2988/// }
    2989/// ```
    2990#[stable(feature = "rust1", since = "1.0.0")]
    2991pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
    2992    fs_imp::read_link(path.as_ref())
    2993}
    2994
    2995/// Returns the canonical, absolute form of a path with all intermediate
    2996/// components normalized and symbolic links resolved.
    2997///
    2998/// # Platform-specific behavior
    2999///
    3000/// This function currently corresponds to the `realpath` function on Unix
    3001/// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
    3002/// Note that this [may change in the future][changes].
    3003///
    3004/// On Windows, this converts the path to use [extended length path][path]
    3005/// syntax, which allows your program to use longer path names, but means you
    3006/// can only join backslash-delimited paths to it, and it may be incompatible
    3007/// with other applications (if passed to the application on the command-line,
    3008/// or written to a file another application may read).
    3009///
    3010/// [changes]: io#platform-specific-behavior
    3011/// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
    3012///
    3013/// # Errors
    3014///
    3015/// This function will return an error in the following situations, but is not
    3016/// limited to just these cases:
    3017///
    3018/// * `path` does not exist.
    3019/// * A non-final component in path is not a directory.
    3020///
    3021/// # Examples
    3022///
    3023/// ```no_run
    3024/// use std::fs;
    3025///
    3026/// fn main() -> std::io::Result<()> {
    3027///     let path = fs::canonicalize("../a/../foo.txt")?;
    3028///     Ok(())
    3029/// }
    3030/// ```
    3031#[doc(alias = "realpath")]
    3032#[doc(alias = "GetFinalPathNameByHandle")]
    3033#[stable(feature = "fs_canonicalize", since = "1.5.0")]
    3034pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
    3035    fs_imp::canonicalize(path.as_ref())
    3036}
    3037
    3038/// Creates a new, empty directory at the provided path.
    3039///
    3040/// # Platform-specific behavior
    3041///
    3042/// This function currently corresponds to the `mkdir` function on Unix
    3043/// and the `CreateDirectoryW` function on Windows.
    3044/// Note that, this [may change in the future][changes].
    3045///
    3046/// [changes]: io#platform-specific-behavior
    3047///
    3048/// **NOTE**: If a parent of the given path doesn't exist, this function will
    3049/// return an error. To create a directory and all its missing parents at the
    3050/// same time, use the [`create_dir_all`] function.
    3051///
    3052/// # Errors
    3053///
    3054/// This function will return an error in the following situations, but is not
    3055/// limited to just these cases:
    3056///
    3057/// * User lacks permissions to create directory at `path`.
    3058/// * A parent of the given path doesn't exist. (To create a directory and all
    3059///   its missing parents at the same time, use the [`create_dir_all`]
    3060///   function.)
    3061/// * `path` already exists.
    3062///
    3063/// # Examples
    3064///
    3065/// ```no_run
    3066/// use std::fs;
    3067///
    3068/// fn main() -> std::io::Result<()> {
    3069///     fs::create_dir("/some/dir")?;
    3070///     Ok(())
    3071/// }
    3072/// ```
    3073#[doc(alias = "mkdir", alias = "CreateDirectory")]
    3074#[stable(feature = "rust1", since = "1.0.0")]
    3075#[cfg_attr(not(test), rustc_diagnostic_item = "fs_create_dir")]
    3076pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
    3077    DirBuilder::new().create(path.as_ref())
    3078}
    3079
    3080/// Recursively create a directory and all of its parent components if they
    3081/// are missing.
    3082///
    3083/// This function is not atomic. If it returns an error, any parent components it was able to create
    3084/// will remain.
    3085///
    3086/// If the empty path is passed to this function, it always succeeds without
    3087/// creating any directories.
    3088///
    3089/// # Platform-specific behavior
    3090///
    3091/// This function currently corresponds to multiple calls to the `mkdir`
    3092/// function on Unix and the `CreateDirectoryW` function on Windows.
    3093///
    3094/// Note that, this [may change in the future][changes].
    3095///
    3096/// [changes]: io#platform-specific-behavior
    3097///
    3098/// # Errors
    3099///
    3100/// The function will return an error if any directory specified in path does not exist and
    3101/// could not be created. There may be other error conditions; see [`fs::create_dir`] for specifics.
    3102///
    3103/// Notable exception is made for situations where any of the directories
    3104/// specified in the `path` could not be created as it was being created concurrently.
    3105/// Such cases are considered to be successful. That is, calling `create_dir_all`
    3106/// concurrently from multiple threads or processes is guaranteed not to fail
    3107/// due to a race condition with itself.
    3108///
    3109/// [`fs::create_dir`]: create_dir
    3110///
    3111/// # Examples
    3112///
    3113/// ```no_run
    3114/// use std::fs;
    3115///
    3116/// fn main() -> std::io::Result<()> {
    3117///     fs::create_dir_all("/some/dir")?;
    3118///     Ok(())
    3119/// }
    3120/// ```
    3121#[stable(feature = "rust1", since = "1.0.0")]
    3122pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
    3123    DirBuilder::new().recursive(true).create(path.as_ref())
    3124}
    3125
    3126/// Removes an empty directory.
    3127///
    3128/// If you want to remove a directory that is not empty, as well as all
    3129/// of its contents recursively, consider using [`remove_dir_all`]
    3130/// instead.
    3131///
    3132/// # Platform-specific behavior
    3133///
    3134/// This function currently corresponds to the `rmdir` function on Unix
    3135/// and the `RemoveDirectory` function on Windows.
    3136/// Note that, this [may change in the future][changes].
    3137///
    3138/// [changes]: io#platform-specific-behavior
    3139///
    3140/// # Errors
    3141///
    3142/// This function will return an error in the following situations, but is not
    3143/// limited to just these cases:
    3144///
    3145/// * `path` doesn't exist.
    3146/// * `path` isn't a directory.
    3147/// * The user lacks permissions to remove the directory at the provided `path`.
    3148/// * The directory isn't empty.
    3149///
    3150/// This function will only ever return an error of kind `NotFound` if the given
    3151/// path does not exist. Note that the inverse is not true,
    3152/// ie. if a path does not exist, its removal may fail for a number of reasons,
    3153/// such as insufficient permissions.
    3154///
    3155/// # Examples
    3156///
    3157/// ```no_run
    3158/// use std::fs;
    3159///
    3160/// fn main() -> std::io::Result<()> {
    3161///     fs::remove_dir("/some/dir")?;
    3162///     Ok(())
    3163/// }
    3164/// ```
    3165#[doc(alias = "rmdir", alias = "RemoveDirectory")]
    3166#[stable(feature = "rust1", since = "1.0.0")]
    3167pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
    3168    fs_imp::remove_dir(path.as_ref())
    3169}
    3170
    3171/// Removes a directory at this path, after removing all its contents. Use
    3172/// carefully!
    3173///
    3174/// This function does **not** follow symbolic links and it will simply remove the
    3175/// symbolic link itself.
    3176///
    3177/// # Platform-specific behavior
    3178///
    3179/// These implementation details [may change in the future][changes].
    3180///
    3181/// - "Unix-like": By default, this function currently corresponds to
    3182/// `openat`, `fdopendir`, `unlinkat` and `lstat`
    3183/// on Unix-family platforms, except where noted otherwise.
    3184/// - "Windows": This function currently corresponds to `CreateFileW`,
    3185/// `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile`.
    3186///
    3187/// ## Time-of-check to time-of-use (TOCTOU) race conditions
    3188/// See the [module-level TOCTOU explanation](self#time-of-check-to-time-of-use-toctou).
    3189///
    3190/// On most platforms, `fs::remove_dir_all` protects against symlink TOCTOU races by default.
    3191/// However, on the following platforms, this protection is not provided and the function should
    3192/// not be used in security-sensitive contexts:
    3193/// - **Miri**: Even when emulating targets where the underlying implementation will protect against
    3194///   TOCTOU races, Miri will not do so.
    3195/// - **Redox OS**: This function does not protect against TOCTOU races, as Redox does not implement
    3196///   the required platform support to do so.
    3197///
    3198/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
    3199/// [changes]: io#platform-specific-behavior
    3200///
    3201/// # Errors
    3202///
    3203/// See [`fs::remove_file`] and [`fs::remove_dir`].
    3204///
    3205/// [`remove_dir_all`] will fail if [`remove_dir`] or [`remove_file`] fail on *any* constituent
    3206/// paths, *including* the root `path`. Consequently,
    3207///
    3208/// - The directory you are deleting *must* exist, meaning that this function is *not idempotent*.
    3209/// - [`remove_dir_all`] will fail if the `path` is *not* a directory.
    3210///
    3211/// Consider ignoring the error if validating the removal is not required for your use case.
    3212///
    3213/// This function may return [`io::ErrorKind::DirectoryNotEmpty`] if the directory is concurrently
    3214/// written into, which typically indicates some contents were removed but not all.
    3215/// [`io::ErrorKind::NotFound`] is only returned if no removal occurs.
    3216///
    3217/// [`fs::remove_file`]: remove_file
    3218/// [`fs::remove_dir`]: remove_dir
    3219///
    3220/// # Examples
    3221///
    3222/// ```no_run
    3223/// use std::fs;
    3224///
    3225/// fn main() -> std::io::Result<()> {
    3226///     fs::remove_dir_all("/some/dir")?;
    3227///     Ok(())
    3228/// }
    3229/// ```
    3230#[stable(feature = "rust1", since = "1.0.0")]
    3231pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
    3232    fs_imp::remove_dir_all(path.as_ref())
    3233}
    3234
    3235/// Returns an iterator over the entries within a directory.
    3236///
    3237/// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
    3238/// New errors may be encountered after an iterator is initially constructed.
    3239/// Entries for the current and parent directories (typically `.` and `..`) are
    3240/// skipped.
    3241///
    3242/// The order in which `read_dir` returns entries can change between calls. If reproducible
    3243/// ordering is required, the entries should be explicitly sorted.
    3244///
    3245/// # Platform-specific behavior
    3246///
    3247/// This function currently corresponds to the `opendir` function on Unix
    3248/// and the `FindFirstFileEx` function on Windows. Advancing the iterator
    3249/// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
    3250/// Note that, this [may change in the future][changes].
    3251///
    3252/// [changes]: io#platform-specific-behavior
    3253///
    3254/// The order in which this iterator returns entries is platform and filesystem
    3255/// dependent.
    3256///
    3257/// # Errors
    3258///
    3259/// This function will return an error in the following situations, but is not
    3260/// limited to just these cases:
    3261///
    3262/// * The provided `path` doesn't exist.
    3263/// * The process lacks permissions to view the contents.
    3264/// * The `path` points at a non-directory file.
    3265///
    3266/// # Examples
    3267///
    3268/// ```
    3269/// use std::io;
    3270/// use std::fs::{self, DirEntry};
    3271/// use std::path::Path;
    3272///
    3273/// // one possible implementation of walking a directory only visiting files
    3274/// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
    3275///     if dir.is_dir() {
    3276///         for entry in fs::read_dir(dir)? {
    3277///             let entry = entry?;
    3278///             let path = entry.path();
    3279///             if path.is_dir() {
    3280///                 visit_dirs(&path, cb)?;
    3281///             } else {
    3282///                 cb(&entry);
    3283///             }
    3284///         }
    3285///     }
    3286///     Ok(())
    3287/// }
    3288/// ```
    3289///
    3290/// ```rust,no_run
    3291/// use std::{fs, io};
    3292///
    3293/// fn main() -> io::Result<()> {
    3294///     let mut entries = fs::read_dir(".")?
    3295///         .map(|res| res.map(|e| e.path()))
    3296///         .collect::<Result<Vec<_>, io::Error>>()?;
    3297///
    3298///     // The order in which `read_dir` returns entries is not guaranteed. If reproducible
    3299///     // ordering is required the entries should be explicitly sorted.
    3300///
    3301///     entries.sort();
    3302///
    3303///     // The entries have now been sorted by their path.
    3304///
    3305///     Ok(())
    3306/// }
    3307/// ```
    3308#[doc(alias = "ls", alias = "opendir", alias = "FindFirstFile", alias = "FindNextFile")]
    3309#[stable(feature = "rust1", since = "1.0.0")]
    3310pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
    3311    fs_imp::read_dir(path.as_ref()).map(ReadDir)
    3312}
    3313
    3314/// Changes the permissions found on a file or a directory.
    3315///
    3316/// # Platform-specific behavior
    3317///
    3318/// This function currently corresponds to the `chmod` function on Unix
    3319/// and the `SetFileAttributes` function on Windows.
    3320/// Note that, this [may change in the future][changes].
    3321///
    3322/// [changes]: io#platform-specific-behavior
    3323///
    3324/// ## Symlinks
    3325/// On UNIX-like systems, this function will update the permission bits
    3326/// of the file pointed to by the symlink.
    3327///
    3328/// Note that this behavior can lead to privilege escalation vulnerabilities,
    3329/// where the ability to create a symlink in one directory allows you to
    3330/// cause the permissions of another file or directory to be modified.
    3331///
    3332/// For this reason, using this function with symlinks should be avoided.
    3333/// When possible, permissions should be set at creation time instead.
    3334///
    3335/// # Rationale
    3336/// POSIX does not specify an `lchmod` function,
    3337/// and symlinks can be followed regardless of what permission bits are set.
    3338///
    3339/// # Errors
    3340///
    3341/// This function will return an error in the following situations, but is not
    3342/// limited to just these cases:
    3343///
    3344/// * `path` does not exist.
    3345/// * The user lacks the permission to change attributes of the file.
    3346///
    3347/// # Examples
    3348///
    3349/// ```no_run
    3350/// use std::fs;
    3351///
    3352/// fn main() -> std::io::Result<()> {
    3353///     let mut perms = fs::metadata("foo.txt")?.permissions();
    3354///     perms.set_readonly(true);
    3355///     fs::set_permissions("foo.txt", perms)?;
    3356///     Ok(())
    3357/// }
    3358/// ```
    3359#[doc(alias = "chmod", alias = "SetFileAttributes")]
    3360#[stable(feature = "set_permissions", since = "1.1.0")]
    3361pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
    3362    fs_imp::set_permissions(path.as_ref(), perm.0)
    3363}
    3364
    3365/// Set the permissions of a file, unless it is a symlink.
    3366///
    3367/// Note that the non-final path elements are allowed to be symlinks.
    3368///
    3369/// # Platform-specific behavior
    3370///
    3371/// Currently unimplemented on Windows.
    3372///
    3373/// On Unix platforms, this results in a [`FilesystemLoop`] error if the last element is a symlink.
    3374///
    3375/// This behavior may change in the future.
    3376///
    3377/// [`FilesystemLoop`]: crate::io::ErrorKind::FilesystemLoop
    3378#[doc(alias = "chmod", alias = "SetFileAttributes")]
    3379#[unstable(feature = "set_permissions_nofollow", issue = "141607")]
    3380pub fn set_permissions_nofollow<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
    3381    fs_imp::set_permissions_nofollow(path.as_ref(), perm)
    3382}
    3383
    3384impl DirBuilder {
    3385    /// Creates a new set of options with default mode/security settings for all
    3386    /// platforms and also non-recursive.
    3387    ///
    3388    /// # Examples
    3389    ///
    3390    /// ```
    3391    /// use std::fs::DirBuilder;
    3392    ///
    3393    /// let builder = DirBuilder::new();
    3394    /// ```
    3395    #[stable(feature = "dir_builder", since = "1.6.0")]
    3396    #[must_use]
    3397    pub fn new() -> DirBuilder {
    3398        DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
    3399    }
    3400
    3401    /// Indicates that directories should be created recursively, creating all
    3402    /// parent directories. Parents that do not exist are created with the same
    3403    /// security and permissions settings.
    3404    ///
    3405    /// This option defaults to `false`.
    3406    ///
    3407    /// # Examples
    3408    ///
    3409    /// ```
    3410    /// use std::fs::DirBuilder;
    3411    ///
    3412    /// let mut builder = DirBuilder::new();
    3413    /// builder.recursive(true);
    3414    /// ```
    3415    #[stable(feature = "dir_builder", since = "1.6.0")]
    3416    pub fn recursive(&mut self, recursive: bool) -> &mut Self {
    3417        self.recursive = recursive;
    3418        self
    3419    }
    3420
    3421    /// Creates the specified directory with the options configured in this
    3422    /// builder.
    3423    ///
    3424    /// It is considered an error if the directory already exists unless
    3425    /// recursive mode is enabled.
    3426    ///
    3427    /// # Examples
    3428    ///
    3429    /// ```no_run
    3430    /// use std::fs::{self, DirBuilder};
    3431    ///
    3432    /// let path = "/tmp/foo/bar/baz";
    3433    /// DirBuilder::new()
    3434    ///     .recursive(true)
    3435    ///     .create(path).unwrap();
    3436    ///
    3437    /// assert!(fs::metadata(path).unwrap().is_dir());
    3438    /// ```
    3439    #[stable(feature = "dir_builder", since = "1.6.0")]
    3440    pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
    3441        self._create(path.as_ref())
    3442    }
    3443
    3444    fn _create(&self, path: &Path) -> io::Result<()> {
    3445        if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
    3446    }
    3447
    3448    fn create_dir_all(&self, path: &Path) -> io::Result<()> {
    3449        // if path's parent is None, it is "/" path, which should
    3450        // return Ok immediately
    3451        if path == Path::new("") || path.parent() == None {
    3452            return Ok(());
    3453        }
    3454
    3455        let ancestors = path.ancestors();
    3456        let mut uncreated_dirs = 0;
    3457
    3458        for ancestor in ancestors {
    3459            // for relative paths like "foo/bar", the parent of
    3460            // "foo" will be "" which there's no need to invoke
    3461            // a mkdir syscall on
    3462            if ancestor == Path::new("") || ancestor.parent() == None {
    3463                break;
    3464            }
    3465
    3466            match self.inner.mkdir(ancestor) {
    3467                Ok(()) => break,
    3468                Err(e) if e.kind() == io::ErrorKind::NotFound => uncreated_dirs += 1,
    3469                // we check if the err is AlreadyExists for two reasons
    3470                //    - in case the path exists as a *file*
    3471                //    - and to avoid calls to .is_dir() in case of other errs
    3472                //      (i.e. PermissionDenied)
    3473                Err(e) if e.kind() == io::ErrorKind::AlreadyExists && ancestor.is_dir() => break,
    3474                Err(e) => return Err(e),
    3475            }
    3476        }
    3477
    3478        // collect only the uncreated directories w/o letting the vec resize
    3479        let mut uncreated_dirs_vec = Vec::with_capacity(uncreated_dirs);
    3480        uncreated_dirs_vec.extend(ancestors.take(uncreated_dirs));
    3481
    3482        for uncreated_dir in uncreated_dirs_vec.iter().rev() {
    3483            if let Err(e) = self.inner.mkdir(uncreated_dir) {
    3484                if e.kind() != io::ErrorKind::AlreadyExists || !uncreated_dir.is_dir() {
    3485                    return Err(e);
    3486                }
    3487            }
    3488        }
    3489
    3490        Ok(())
    3491    }
    3492}
    3493
    3494impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
    3495    #[inline]
    3496    fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
    3497        &mut self.inner
    3498    }
    3499}
    3500
    3501/// Returns `Ok(true)` if the path points at an existing entity.
    3502///
    3503/// This function will traverse symbolic links to query information about the
    3504/// destination file. In case of broken symbolic links this will return `Ok(false)`.
    3505///
    3506/// As opposed to the [`Path::exists`] method, this will only return `Ok(true)` or `Ok(false)`
    3507/// if the path was _verified_ to exist or not exist. If its existence can neither be confirmed
    3508/// nor denied, an `Err(_)` will be propagated instead. This can be the case if e.g. listing
    3509/// permission is denied on one of the parent directories.
    3510///
    3511/// Note that while this avoids some pitfalls of the `exists()` method, it still can not
    3512/// prevent time-of-check to time-of-use ([TOCTOU]) bugs. You should only use it in scenarios
    3513/// where those bugs are not an issue.
    3514///
    3515/// # Examples
    3516///
    3517/// ```no_run
    3518/// use std::fs;
    3519///
    3520/// assert!(!fs::exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
    3521/// assert!(fs::exists("/root/secret_file.txt").is_err());
    3522/// ```
    3523///
    3524/// [`Path::exists`]: crate::path::Path::exists
    3525/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
    3526#[stable(feature = "fs_try_exists", since = "1.81.0")]
    3527#[inline]
    3528pub fn exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
    3529    fs_imp::exists(path.as_ref())
    3530}