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