Skip to main content

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