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 with a different OS handle referring to
1154    /// the same underlying system resource as the existing `File` instance.
1155    /// Reads, writes, and seeks will affect 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 of overwriting
2039    /// previous contents. The `write` setting is ignored when `append` is true, i.e.,
2040    /// `.write(true).append(true).open(...)` has the same effect as `.append(true).open(...)`.
2041    ///
2042    /// Append mode guarantees that writes will be positioned at the current end of file,
2043    /// even when there are other processes or threads appending to the same file. This is
2044    /// a race-free version of <code>[seek]\([SeekFrom]::[End]\(0))</code> followed by `write()`,
2045    /// working correctly even if there are concurrent writers.
2046    ///
2047    /// Keep in mind that this does not necessarily guarantee that data appended by
2048    /// different processes or threads does not interleave. The amount of data accepted a
2049    /// single `write()` call depends on the operating system and file system. A
2050    /// successful `write()` is allowed to write only part of the given data, so even if
2051    /// you're careful to provide the whole message in a single call to `write()`, there
2052    /// is no guarantee that it will be written out in full. If you rely on the filesystem
2053    /// accepting the message in a single write, make sure that all data that belongs
2054    /// together is written in one operation. This can be done by concatenating strings
2055    /// before passing them to [`write()`].
2056    ///
2057    /// If a file is opened with both read and append access, beware that after
2058    /// opening, and after every write, the position for reading may be set at the
2059    /// end of the file. So, before writing, save the current position (using
2060    /// <code>[Seek]::[stream_position]</code>), and restore it before the next read.
2061    ///
2062    /// ## Note
2063    ///
2064    /// This function doesn't create the file if it doesn't exist. Use the
2065    /// [`OpenOptions::create`] method to do so.
2066    ///
2067    /// [`write()`]: Write::write "io::Write::write"
2068    /// [`flush()`]: Write::flush "io::Write::flush"
2069    /// [stream_position]: Seek::stream_position "io::Seek::stream_position"
2070    /// [seek]: Seek::seek "io::Seek::seek"
2071    /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
2072    /// [End]: SeekFrom::End "io::SeekFrom::End"
2073    ///
2074    /// # Examples
2075    ///
2076    /// ```no_run
2077    /// use std::fs::OpenOptions;
2078    ///
2079    /// let file = OpenOptions::new().append(true).open("foo.txt");
2080    /// ```
2081    #[stable(feature = "rust1", since = "1.0.0")]
2082    pub fn append(&mut self, append: bool) -> &mut Self {
2083        self.0.append(append);
2084        self
2085    }
2086
2087    /// Sets the option for truncating a previous file.
2088    ///
2089    /// If a file is successfully opened with this option set to true, it will truncate
2090    /// the file to 0 length if it already exists.
2091    ///
2092    /// The file must be opened with write access for truncate to work.
2093    ///
2094    /// # Examples
2095    ///
2096    /// ```no_run
2097    /// use std::fs::OpenOptions;
2098    ///
2099    /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
2100    /// ```
2101    #[stable(feature = "rust1", since = "1.0.0")]
2102    pub fn truncate(&mut self, truncate: bool) -> &mut Self {
2103        self.0.truncate(truncate);
2104        self
2105    }
2106
2107    /// Sets the option to create a new file, or open it if it already exists.
2108    ///
2109    /// In order for the file to be created, [`OpenOptions::write`] or
2110    /// [`OpenOptions::append`] access must be used.
2111    ///
2112    /// See also [`std::fs::write()`][self::write] for a simple function to
2113    /// create a file with some given data.
2114    ///
2115    /// # Errors
2116    ///
2117    /// If `.create(true)` is set without `.write(true)` or `.append(true)`,
2118    /// calling [`open`](Self::open) will fail with [`InvalidInput`](io::ErrorKind::InvalidInput) error.
2119    /// # Examples
2120    ///
2121    /// ```no_run
2122    /// use std::fs::OpenOptions;
2123    ///
2124    /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
2125    /// ```
2126    #[stable(feature = "rust1", since = "1.0.0")]
2127    pub fn create(&mut self, create: bool) -> &mut Self {
2128        self.0.create(create);
2129        self
2130    }
2131
2132    /// Sets the option to create a new file, failing if it already exists.
2133    ///
2134    /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
2135    /// way, if the call succeeds, the file returned is guaranteed to be new.
2136    /// If a file exists at the target location, creating a new file will fail with [`AlreadyExists`]
2137    /// or another error based on the situation. See [`OpenOptions::open`] for a
2138    /// non-exhaustive list of likely errors.
2139    ///
2140    /// This option is useful because it is atomic. Otherwise between checking
2141    /// whether a file exists and creating a new one, the file may have been
2142    /// created by another process (a [TOCTOU] race condition / attack).
2143    ///
2144    /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
2145    /// ignored.
2146    ///
2147    /// The file must be opened with write or append access in order to create
2148    /// a new file.
2149    ///
2150    /// [`.create()`]: OpenOptions::create
2151    /// [`.truncate()`]: OpenOptions::truncate
2152    /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
2153    /// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
2154    ///
2155    /// # Examples
2156    ///
2157    /// ```no_run
2158    /// use std::fs::OpenOptions;
2159    ///
2160    /// let file = OpenOptions::new().write(true)
2161    ///                              .create_new(true)
2162    ///                              .open("foo.txt");
2163    /// ```
2164    #[stable(feature = "expand_open_options2", since = "1.9.0")]
2165    pub fn create_new(&mut self, create_new: bool) -> &mut Self {
2166        self.0.create_new(create_new);
2167        self
2168    }
2169
2170    /// Opens a file at `path` with the options specified by `self`.
2171    ///
2172    /// # Errors
2173    ///
2174    /// This function will return an error under a number of different
2175    /// circumstances. Some of these error conditions are listed here, together
2176    /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
2177    /// part of the compatibility contract of the function.
2178    ///
2179    /// * [`NotFound`]: The specified file does not exist and neither `create`
2180    ///   or `create_new` is set.
2181    /// * [`NotFound`]: One of the directory components of the file path does
2182    ///   not exist.
2183    /// * [`PermissionDenied`]: The user lacks permission to get the specified
2184    ///   access rights for the file.
2185    /// * [`PermissionDenied`]: The user lacks permission to open one of the
2186    ///   directory components of the specified path.
2187    /// * [`AlreadyExists`]: `create_new` was specified and the file already
2188    ///   exists.
2189    /// * [`InvalidInput`]: Invalid combinations of open options (truncate
2190    ///   without write access, create without write or append access,
2191    ///   no access mode set, etc.).
2192    ///
2193    /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
2194    /// * One of the directory components of the specified file path
2195    ///   was not, in fact, a directory.
2196    /// * Filesystem-level errors: full disk, write permission
2197    ///   requested on a read-only file system, exceeded disk quota, too many
2198    ///   open files, too long filename, too many symbolic links in the
2199    ///   specified path (Unix-like systems only), etc.
2200    ///
2201    /// # Examples
2202    ///
2203    /// ```no_run
2204    /// use std::fs::OpenOptions;
2205    ///
2206    /// let file = OpenOptions::new().read(true).open("foo.txt");
2207    /// ```
2208    ///
2209    /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
2210    /// [`InvalidInput`]: io::ErrorKind::InvalidInput
2211    /// [`NotFound`]: io::ErrorKind::NotFound
2212    /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
2213    #[stable(feature = "rust1", since = "1.0.0")]
2214    pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
2215        self._open(path.as_ref())
2216    }
2217
2218    fn _open(&self, path: &Path) -> io::Result<File> {
2219        fs_imp::File::open(path, &self.0).map(|inner| File { inner })
2220    }
2221}
2222
2223impl AsInner<fs_imp::OpenOptions> for OpenOptions {
2224    #[inline]
2225    fn as_inner(&self) -> &fs_imp::OpenOptions {
2226        &self.0
2227    }
2228}
2229
2230impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
2231    #[inline]
2232    fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
2233        &mut self.0
2234    }
2235}
2236
2237impl Metadata {
2238    /// Returns the file type for this metadata.
2239    ///
2240    /// # Examples
2241    ///
2242    /// ```no_run
2243    /// fn main() -> std::io::Result<()> {
2244    ///     use std::fs;
2245    ///
2246    ///     let metadata = fs::metadata("foo.txt")?;
2247    ///
2248    ///     println!("{:?}", metadata.file_type());
2249    ///     Ok(())
2250    /// }
2251    /// ```
2252    #[must_use]
2253    #[stable(feature = "file_type", since = "1.1.0")]
2254    pub fn file_type(&self) -> FileType {
2255        FileType(self.0.file_type())
2256    }
2257
2258    /// Returns `true` if this metadata is for a directory. The result is mutually exclusive to the
2259    /// result of [`Metadata::is_file`] and [`Metadata::is_symlink`] (i.e., at most one of these
2260    /// three methods returns `true`).
2261    ///
2262    /// # Examples
2263    ///
2264    /// ```no_run
2265    /// fn main() -> std::io::Result<()> {
2266    ///     use std::fs;
2267    ///
2268    ///     let metadata = fs::metadata("foo.txt")?;
2269    ///
2270    ///     assert!(!metadata.is_dir());
2271    ///     Ok(())
2272    /// }
2273    /// ```
2274    #[must_use]
2275    #[stable(feature = "rust1", since = "1.0.0")]
2276    pub fn is_dir(&self) -> bool {
2277        self.file_type().is_dir()
2278    }
2279
2280    /// Returns `true` if this metadata is for a regular file. The result is mutually exclusive to
2281    /// the result of [`Metadata::is_dir`] and [`Metadata::is_symlink`] (i.e., at most one of these
2282    /// three methods returns `true`).
2283    ///
2284    /// When the goal is simply to read from (or write to) the source, the most
2285    /// reliable way to test the source can be read (or written to) is to open
2286    /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2287    /// a Unix-like system for example. See [`File::open`] or
2288    /// [`OpenOptions::open`] for more information.
2289    ///
2290    /// # Examples
2291    ///
2292    /// ```no_run
2293    /// use std::fs;
2294    ///
2295    /// fn main() -> std::io::Result<()> {
2296    ///     let metadata = fs::metadata("foo.txt")?;
2297    ///
2298    ///     assert!(metadata.is_file());
2299    ///     Ok(())
2300    /// }
2301    /// ```
2302    #[must_use]
2303    #[stable(feature = "rust1", since = "1.0.0")]
2304    pub fn is_file(&self) -> bool {
2305        self.file_type().is_file()
2306    }
2307
2308    /// Returns `true` if this metadata is for a symbolic link.
2309    ///
2310    /// # Examples
2311    ///
2312    #[cfg_attr(unix, doc = "```no_run")]
2313    #[cfg_attr(not(unix), doc = "```ignore")]
2314    /// use std::fs;
2315    /// use std::path::Path;
2316    /// use std::os::unix::fs::symlink;
2317    ///
2318    /// fn main() -> std::io::Result<()> {
2319    ///     let link_path = Path::new("link");
2320    ///     symlink("/origin_does_not_exist/", link_path)?;
2321    ///
2322    ///     let metadata = fs::symlink_metadata(link_path)?;
2323    ///
2324    ///     assert!(metadata.is_symlink());
2325    ///     Ok(())
2326    /// }
2327    /// ```
2328    #[must_use]
2329    #[stable(feature = "is_symlink", since = "1.58.0")]
2330    pub fn is_symlink(&self) -> bool {
2331        self.file_type().is_symlink()
2332    }
2333
2334    /// Returns the size of the file, in bytes, this metadata is for.
2335    ///
2336    /// # Examples
2337    ///
2338    /// ```no_run
2339    /// use std::fs;
2340    ///
2341    /// fn main() -> std::io::Result<()> {
2342    ///     let metadata = fs::metadata("foo.txt")?;
2343    ///
2344    ///     assert_eq!(0, metadata.len());
2345    ///     Ok(())
2346    /// }
2347    /// ```
2348    #[must_use]
2349    #[stable(feature = "rust1", since = "1.0.0")]
2350    pub fn len(&self) -> u64 {
2351        self.0.size()
2352    }
2353
2354    /// Returns the permissions of the file this metadata is for.
2355    ///
2356    /// # Examples
2357    ///
2358    /// ```no_run
2359    /// use std::fs;
2360    ///
2361    /// fn main() -> std::io::Result<()> {
2362    ///     let metadata = fs::metadata("foo.txt")?;
2363    ///
2364    ///     assert!(!metadata.permissions().readonly());
2365    ///     Ok(())
2366    /// }
2367    /// ```
2368    #[must_use]
2369    #[stable(feature = "rust1", since = "1.0.0")]
2370    pub fn permissions(&self) -> Permissions {
2371        Permissions(self.0.perm())
2372    }
2373
2374    /// Returns the last modification time listed in this metadata.
2375    ///
2376    /// The returned value corresponds to the `mtime` field of `stat` on Unix
2377    /// platforms and the `ftLastWriteTime` field on Windows platforms.
2378    ///
2379    /// # Errors
2380    ///
2381    /// This field might not be available on all platforms, and will return an
2382    /// `Err` on platforms where it is not available.
2383    ///
2384    /// # Examples
2385    ///
2386    /// ```no_run
2387    /// use std::fs;
2388    ///
2389    /// fn main() -> std::io::Result<()> {
2390    ///     let metadata = fs::metadata("foo.txt")?;
2391    ///
2392    ///     if let Ok(time) = metadata.modified() {
2393    ///         println!("{time:?}");
2394    ///     } else {
2395    ///         println!("Not supported on this platform");
2396    ///     }
2397    ///     Ok(())
2398    /// }
2399    /// ```
2400    #[doc(alias = "mtime", alias = "ftLastWriteTime")]
2401    #[stable(feature = "fs_time", since = "1.10.0")]
2402    pub fn modified(&self) -> io::Result<SystemTime> {
2403        self.0.modified().map(FromInner::from_inner)
2404    }
2405
2406    /// Returns the last access time of this metadata.
2407    ///
2408    /// The returned value corresponds to the `atime` field of `stat` on Unix
2409    /// platforms and the `ftLastAccessTime` field on Windows platforms.
2410    ///
2411    /// Note that not all platforms will keep this field update in a file's
2412    /// metadata, for example Windows has an option to disable updating this
2413    /// time when files are accessed and Linux similarly has `noatime`.
2414    ///
2415    /// # Errors
2416    ///
2417    /// This field might not be available on all platforms, and will return an
2418    /// `Err` on platforms where it is not available.
2419    ///
2420    /// # Examples
2421    ///
2422    /// ```no_run
2423    /// use std::fs;
2424    ///
2425    /// fn main() -> std::io::Result<()> {
2426    ///     let metadata = fs::metadata("foo.txt")?;
2427    ///
2428    ///     if let Ok(time) = metadata.accessed() {
2429    ///         println!("{time:?}");
2430    ///     } else {
2431    ///         println!("Not supported on this platform");
2432    ///     }
2433    ///     Ok(())
2434    /// }
2435    /// ```
2436    #[doc(alias = "atime", alias = "ftLastAccessTime")]
2437    #[stable(feature = "fs_time", since = "1.10.0")]
2438    pub fn accessed(&self) -> io::Result<SystemTime> {
2439        self.0.accessed().map(FromInner::from_inner)
2440    }
2441
2442    /// Returns the creation time listed in this metadata.
2443    ///
2444    /// The returned value corresponds to the `btime` field of `statx` on
2445    /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
2446    /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
2447    ///
2448    /// # Errors
2449    ///
2450    /// This field might not be available on all platforms, and will return an
2451    /// `Err` on platforms or filesystems where it is not available.
2452    ///
2453    /// # Examples
2454    ///
2455    /// ```no_run
2456    /// use std::fs;
2457    ///
2458    /// fn main() -> std::io::Result<()> {
2459    ///     let metadata = fs::metadata("foo.txt")?;
2460    ///
2461    ///     if let Ok(time) = metadata.created() {
2462    ///         println!("{time:?}");
2463    ///     } else {
2464    ///         println!("Not supported on this platform or filesystem");
2465    ///     }
2466    ///     Ok(())
2467    /// }
2468    /// ```
2469    #[doc(alias = "btime", alias = "birthtime", alias = "ftCreationTime")]
2470    #[stable(feature = "fs_time", since = "1.10.0")]
2471    pub fn created(&self) -> io::Result<SystemTime> {
2472        self.0.created().map(FromInner::from_inner)
2473    }
2474}
2475
2476#[stable(feature = "std_debug", since = "1.16.0")]
2477impl fmt::Debug for Metadata {
2478    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2479        let mut debug = f.debug_struct("Metadata");
2480        debug.field("file_type", &self.file_type());
2481        debug.field("permissions", &self.permissions());
2482        debug.field("len", &self.len());
2483        if let Ok(modified) = self.modified() {
2484            debug.field("modified", &modified);
2485        }
2486        if let Ok(accessed) = self.accessed() {
2487            debug.field("accessed", &accessed);
2488        }
2489        if let Ok(created) = self.created() {
2490            debug.field("created", &created);
2491        }
2492        debug.finish_non_exhaustive()
2493    }
2494}
2495
2496impl IntoInner<fs_imp::FileAttr> for Metadata {
2497    fn into_inner(self) -> fs_imp::FileAttr {
2498        self.0
2499    }
2500}
2501
2502impl AsInner<fs_imp::FileAttr> for Metadata {
2503    #[inline]
2504    fn as_inner(&self) -> &fs_imp::FileAttr {
2505        &self.0
2506    }
2507}
2508
2509impl FromInner<fs_imp::FileAttr> for Metadata {
2510    fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
2511        Metadata(attr)
2512    }
2513}
2514
2515impl FileTimes {
2516    /// Creates a new `FileTimes` with no times set.
2517    ///
2518    /// Using the resulting `FileTimes` in [`File::set_times`] will not modify any timestamps.
2519    #[stable(feature = "file_set_times", since = "1.75.0")]
2520    pub fn new() -> Self {
2521        Self::default()
2522    }
2523
2524    /// Set the last access time of a file.
2525    #[stable(feature = "file_set_times", since = "1.75.0")]
2526    pub fn set_accessed(mut self, t: SystemTime) -> Self {
2527        self.0.set_accessed(t.into_inner());
2528        self
2529    }
2530
2531    /// Set the last modified time of a file.
2532    #[stable(feature = "file_set_times", since = "1.75.0")]
2533    pub fn set_modified(mut self, t: SystemTime) -> Self {
2534        self.0.set_modified(t.into_inner());
2535        self
2536    }
2537}
2538
2539impl AsInnerMut<fs_imp::FileTimes> for FileTimes {
2540    fn as_inner_mut(&mut self) -> &mut fs_imp::FileTimes {
2541        &mut self.0
2542    }
2543}
2544
2545impl Permissions {
2546    /// Returns `true` if these permissions describe a readonly (unwritable) file.
2547    ///
2548    /// # Note
2549    ///
2550    /// This function does not take Access Control Lists (ACLs), Unix group
2551    /// membership and other nuances into account.
2552    /// Therefore the return value of this function cannot be relied upon
2553    /// to predict whether attempts to read or write the file will actually succeed.
2554    ///
2555    /// # Windows
2556    ///
2557    /// On Windows this returns [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
2558    /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
2559    /// but the user may still have permission to change this flag. If
2560    /// `FILE_ATTRIBUTE_READONLY` is *not* set then writes may still fail due
2561    /// to lack of write permission.
2562    /// The behavior of this attribute for directories depends on the Windows
2563    /// version.
2564    ///
2565    /// # Unix (including macOS)
2566    ///
2567    /// On Unix-based platforms this checks if *any* of the owner, group or others
2568    /// write permission bits are set. It does not consider anything else, including:
2569    ///
2570    /// * Whether the current user is in the file's assigned group.
2571    /// * Permissions granted by ACL.
2572    /// * That `root` user can write to files that do not have any write bits set.
2573    /// * Writable files on a filesystem that is mounted read-only.
2574    ///
2575    /// The [`PermissionsExt`] trait gives direct access to the permission bits but
2576    /// also does not read ACLs.
2577    ///
2578    /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
2579    ///
2580    /// # Examples
2581    ///
2582    /// ```no_run
2583    /// use std::fs::File;
2584    ///
2585    /// fn main() -> std::io::Result<()> {
2586    ///     let mut f = File::create("foo.txt")?;
2587    ///     let metadata = f.metadata()?;
2588    ///
2589    ///     assert_eq!(false, metadata.permissions().readonly());
2590    ///     Ok(())
2591    /// }
2592    /// ```
2593    #[must_use = "call `set_readonly` to modify the readonly flag"]
2594    #[stable(feature = "rust1", since = "1.0.0")]
2595    pub fn readonly(&self) -> bool {
2596        self.0.readonly()
2597    }
2598
2599    /// Modifies the readonly flag for this set of permissions. If the
2600    /// `readonly` argument is `true`, using the resulting `Permission` will
2601    /// update file permissions to forbid writing. Conversely, if it's `false`,
2602    /// using the resulting `Permission` will update file permissions to allow
2603    /// writing.
2604    ///
2605    /// This operation does **not** modify the files attributes. This only
2606    /// changes the in-memory value of these attributes for this `Permissions`
2607    /// instance. To modify the files attributes use the [`set_permissions`]
2608    /// function which commits these attribute changes to the file.
2609    ///
2610    /// # Note
2611    ///
2612    /// `set_readonly(false)` makes the file *world-writable* on Unix.
2613    /// You can use the [`PermissionsExt`] trait on Unix to avoid this issue.
2614    ///
2615    /// It also does not take Access Control Lists (ACLs) or Unix group
2616    /// membership into account.
2617    ///
2618    /// # Windows
2619    ///
2620    /// On Windows this sets or clears [`FILE_ATTRIBUTE_READONLY`](https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants).
2621    /// If `FILE_ATTRIBUTE_READONLY` is set then writes to the file will fail
2622    /// but the user may still have permission to change this flag. If
2623    /// `FILE_ATTRIBUTE_READONLY` is *not* set then the write may still fail if
2624    /// the user does not have permission to write to the file.
2625    ///
2626    /// In Windows 7 and earlier this attribute prevents deleting empty
2627    /// directories. It does not prevent modifying the directory contents.
2628    /// On later versions of Windows this attribute is ignored for directories.
2629    ///
2630    /// # Unix (including macOS)
2631    ///
2632    /// On Unix-based platforms this sets or clears the write access bit for
2633    /// the owner, group *and* others, equivalent to `chmod a+w <file>`
2634    /// or `chmod a-w <file>` respectively. The latter will grant write access
2635    /// to all users! You can use the [`PermissionsExt`] trait on Unix
2636    /// to avoid this issue.
2637    ///
2638    /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
2639    ///
2640    /// # Examples
2641    ///
2642    /// ```no_run
2643    /// use std::fs::File;
2644    ///
2645    /// fn main() -> std::io::Result<()> {
2646    ///     let f = File::create("foo.txt")?;
2647    ///     let metadata = f.metadata()?;
2648    ///     let mut permissions = metadata.permissions();
2649    ///
2650    ///     permissions.set_readonly(true);
2651    ///
2652    ///     // filesystem doesn't change, only the in memory state of the
2653    ///     // readonly permission
2654    ///     assert_eq!(false, metadata.permissions().readonly());
2655    ///
2656    ///     // just this particular `permissions`.
2657    ///     assert_eq!(true, permissions.readonly());
2658    ///     Ok(())
2659    /// }
2660    /// ```
2661    #[stable(feature = "rust1", since = "1.0.0")]
2662    pub fn set_readonly(&mut self, readonly: bool) {
2663        self.0.set_readonly(readonly)
2664    }
2665}
2666
2667impl FileType {
2668    /// Tests whether this file type represents a directory. The
2669    /// result is mutually exclusive to the results of
2670    /// [`is_file`] and [`is_symlink`]; only zero or one of these
2671    /// tests may pass.
2672    ///
2673    /// [`is_file`]: FileType::is_file
2674    /// [`is_symlink`]: FileType::is_symlink
2675    ///
2676    /// # Examples
2677    ///
2678    /// ```no_run
2679    /// fn main() -> std::io::Result<()> {
2680    ///     use std::fs;
2681    ///
2682    ///     let metadata = fs::metadata("foo.txt")?;
2683    ///     let file_type = metadata.file_type();
2684    ///
2685    ///     assert_eq!(file_type.is_dir(), false);
2686    ///     Ok(())
2687    /// }
2688    /// ```
2689    #[must_use]
2690    #[stable(feature = "file_type", since = "1.1.0")]
2691    pub fn is_dir(&self) -> bool {
2692        self.0.is_dir()
2693    }
2694
2695    /// Tests whether this file type represents a regular file.
2696    /// The result is mutually exclusive to the results of
2697    /// [`is_dir`] and [`is_symlink`]; only zero or one of these
2698    /// tests may pass.
2699    ///
2700    /// When the goal is simply to read from (or write to) the source, the most
2701    /// reliable way to test the source can be read (or written to) is to open
2702    /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
2703    /// a Unix-like system for example. See [`File::open`] or
2704    /// [`OpenOptions::open`] for more information.
2705    ///
2706    /// [`is_dir`]: FileType::is_dir
2707    /// [`is_symlink`]: FileType::is_symlink
2708    ///
2709    /// # Examples
2710    ///
2711    /// ```no_run
2712    /// fn main() -> std::io::Result<()> {
2713    ///     use std::fs;
2714    ///
2715    ///     let metadata = fs::metadata("foo.txt")?;
2716    ///     let file_type = metadata.file_type();
2717    ///
2718    ///     assert_eq!(file_type.is_file(), true);
2719    ///     Ok(())
2720    /// }
2721    /// ```
2722    #[must_use]
2723    #[stable(feature = "file_type", since = "1.1.0")]
2724    pub fn is_file(&self) -> bool {
2725        self.0.is_file()
2726    }
2727
2728    /// Tests whether this file type represents a symbolic link.
2729    /// The result is mutually exclusive to the results of
2730    /// [`is_dir`] and [`is_file`]; only zero or one of these
2731    /// tests may pass.
2732    ///
2733    /// The underlying [`Metadata`] struct needs to be retrieved
2734    /// with the [`fs::symlink_metadata`] function and not the
2735    /// [`fs::metadata`] function. The [`fs::metadata`] function
2736    /// follows symbolic links, so [`is_symlink`] would always
2737    /// return `false` for the target file.
2738    ///
2739    /// [`fs::metadata`]: metadata
2740    /// [`fs::symlink_metadata`]: symlink_metadata
2741    /// [`is_dir`]: FileType::is_dir
2742    /// [`is_file`]: FileType::is_file
2743    /// [`is_symlink`]: FileType::is_symlink
2744    ///
2745    /// # Examples
2746    ///
2747    /// ```no_run
2748    /// use std::fs;
2749    ///
2750    /// fn main() -> std::io::Result<()> {
2751    ///     let metadata = fs::symlink_metadata("foo.txt")?;
2752    ///     let file_type = metadata.file_type();
2753    ///
2754    ///     assert_eq!(file_type.is_symlink(), false);
2755    ///     Ok(())
2756    /// }
2757    /// ```
2758    #[must_use]
2759    #[stable(feature = "file_type", since = "1.1.0")]
2760    pub fn is_symlink(&self) -> bool {
2761        self.0.is_symlink()
2762    }
2763}
2764
2765#[stable(feature = "std_debug", since = "1.16.0")]
2766impl fmt::Debug for FileType {
2767    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2768        f.debug_struct("FileType")
2769            .field("is_file", &self.is_file())
2770            .field("is_dir", &self.is_dir())
2771            .field("is_symlink", &self.is_symlink())
2772            .finish_non_exhaustive()
2773    }
2774}
2775
2776impl AsInner<fs_imp::FileType> for FileType {
2777    #[inline]
2778    fn as_inner(&self) -> &fs_imp::FileType {
2779        &self.0
2780    }
2781}
2782
2783impl FromInner<fs_imp::FilePermissions> for Permissions {
2784    fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
2785        Permissions(f)
2786    }
2787}
2788
2789impl AsInner<fs_imp::FilePermissions> for Permissions {
2790    #[inline]
2791    fn as_inner(&self) -> &fs_imp::FilePermissions {
2792        &self.0
2793    }
2794}
2795
2796impl ReadDir {
2797    /// Returns a handle for the directory this `ReadDir` is reading.
2798    ///
2799    /// Whenever possible, the new handle will be created in a race-free manner from the underlying
2800    /// handle used by `ReadDir`. However, this may fall back to opening a new handle based on the
2801    /// path, which is subject to race conditions if the file system has changed since the `ReadDir`
2802    /// was created.
2803    // FIXME: before stabilization, ensure that we have a race-free implementation on Windows!
2804    #[unstable(feature = "dirfd", issue = "120426")]
2805    pub fn dir(&self) -> io::Result<Dir> {
2806        self.0.dir().map(|d| Dir { inner: d })
2807    }
2808}
2809
2810#[stable(feature = "rust1", since = "1.0.0")]
2811impl Iterator for ReadDir {
2812    type Item = io::Result<DirEntry>;
2813
2814    fn next(&mut self) -> Option<io::Result<DirEntry>> {
2815        self.0.next().map(|entry| entry.map(DirEntry))
2816    }
2817}
2818
2819impl DirEntry {
2820    /// Returns the full path to the file that this entry represents.
2821    ///
2822    /// The full path is created by joining the original path to `read_dir`
2823    /// with the filename of this entry.
2824    ///
2825    /// # Examples
2826    ///
2827    /// ```no_run
2828    /// use std::fs;
2829    ///
2830    /// fn main() -> std::io::Result<()> {
2831    ///     for entry in fs::read_dir(".")? {
2832    ///         let dir = entry?;
2833    ///         println!("{:?}", dir.path());
2834    ///     }
2835    ///     Ok(())
2836    /// }
2837    /// ```
2838    ///
2839    /// This prints output like:
2840    ///
2841    /// ```text
2842    /// "./whatever.txt"
2843    /// "./foo.html"
2844    /// "./hello_world.rs"
2845    /// ```
2846    ///
2847    /// The exact text, of course, depends on what files you have in `.`.
2848    #[must_use]
2849    #[stable(feature = "rust1", since = "1.0.0")]
2850    pub fn path(&self) -> PathBuf {
2851        self.0.path()
2852    }
2853
2854    /// Returns the metadata for the file that this entry points at.
2855    ///
2856    /// This function will not traverse symlinks if this entry points at a
2857    /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
2858    ///
2859    /// [`fs::metadata`]: metadata
2860    /// [`fs::File::metadata`]: File::metadata
2861    ///
2862    /// # Platform-specific behavior
2863    ///
2864    /// On Windows this function is cheap to call (no extra system calls
2865    /// needed), but on Unix platforms this function is the equivalent of
2866    /// calling `symlink_metadata` on the path. In that case, if the file has been renamed or
2867    /// replaced since the `DirEntry` was created, this can fail or return the metadata of a
2868    /// different file!
2869    ///
2870    /// # Examples
2871    ///
2872    /// ```
2873    /// # if cfg!(all(windows, skip_unsupported_miri_tests)) { return; }
2874    /// use std::fs;
2875    ///
2876    /// if let Ok(entries) = fs::read_dir(".") {
2877    ///     for entry in entries {
2878    ///         if let Ok(entry) = entry {
2879    ///             // Here, `entry` is a `DirEntry`.
2880    ///             if let Ok(metadata) = entry.metadata() {
2881    ///                 // Now let's show our entry's permissions!
2882    ///                 println!("{:?}: {:?}", entry.path(), metadata.permissions());
2883    ///             } else {
2884    ///                 println!("Couldn't get metadata for {:?}", entry.path());
2885    ///             }
2886    ///         }
2887    ///     }
2888    /// }
2889    /// ```
2890    #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2891    pub fn metadata(&self) -> io::Result<Metadata> {
2892        self.0.metadata().map(Metadata)
2893    }
2894
2895    /// Returns the file type for the file that this entry points at.
2896    ///
2897    /// This function will not traverse symlinks if this entry points at a
2898    /// symlink.
2899    ///
2900    /// # Platform-specific behavior
2901    ///
2902    /// On Windows and most Unix platforms and file systems this function is free (no extra
2903    /// system calls needed), but some Unix platforms or file systems may require the equivalent of
2904    /// calling `symlink_metadata` to learn about the target file type. In that case, if the file
2905    /// has been renamed or replaced since the `DirEntry` was created, this can fail or return the
2906    /// file type of a different file!
2907    ///
2908    /// # Examples
2909    ///
2910    /// ```
2911    /// # if cfg!(all(windows, skip_unsupported_miri_tests)) { return; }
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    /// # if cfg!(all(windows, skip_unsupported_miri_tests)) { return; }
2946    /// use std::fs;
2947    ///
2948    /// if let Ok(entries) = fs::read_dir(".") {
2949    ///     for entry in entries {
2950    ///         if let Ok(entry) = entry {
2951    ///             // Here, `entry` is a `DirEntry`.
2952    ///             println!("{:?}", entry.file_name());
2953    ///         }
2954    ///     }
2955    /// }
2956    /// ```
2957    #[must_use]
2958    #[stable(feature = "dir_entry_ext", since = "1.1.0")]
2959    pub fn file_name(&self) -> OsString {
2960        self.0.file_name()
2961    }
2962}
2963
2964#[stable(feature = "dir_entry_debug", since = "1.13.0")]
2965impl fmt::Debug for DirEntry {
2966    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2967        f.debug_tuple("DirEntry").field(&self.path()).finish()
2968    }
2969}
2970
2971impl AsInner<fs_imp::DirEntry> for DirEntry {
2972    #[inline]
2973    fn as_inner(&self) -> &fs_imp::DirEntry {
2974        &self.0
2975    }
2976}
2977
2978/// Removes a file from the filesystem.
2979///
2980/// Note that there is no
2981/// guarantee that the file is immediately deleted (e.g., depending on
2982/// platform, other open file descriptors may prevent immediate removal).
2983///
2984/// # Platform-specific behavior
2985///
2986/// This function currently corresponds to the `unlink` function on Unix.
2987/// On Windows, `DeleteFile` is used or `CreateFileW` and `SetInformationByHandle` for readonly files.
2988/// Note that, this [may change in the future][changes].
2989///
2990/// On Windows, symbolic links to directories cannot currently be removed with this function.
2991/// Use [`remove_dir`] for that purpose.
2992///
2993/// [changes]: io#platform-specific-behavior
2994///
2995/// # Errors
2996///
2997/// This function will return an error in the following situations, but is not
2998/// limited to just these cases:
2999///
3000/// * `path` points to a directory.
3001/// * The file doesn't exist.
3002/// * The user lacks permissions to remove the file.
3003///
3004/// This function will only ever return an error of kind `NotFound` if the given
3005/// path does not exist. Note that the inverse is not true,
3006/// i.e. if a path does not exist, its removal may fail for a number of reasons,
3007/// such as insufficient permissions.
3008///
3009/// # Examples
3010///
3011/// ```no_run
3012/// use std::fs;
3013///
3014/// fn main() -> std::io::Result<()> {
3015///     fs::remove_file("a.txt")?;
3016///     Ok(())
3017/// }
3018/// ```
3019#[doc(alias = "rm", alias = "unlink", alias = "DeleteFile")]
3020#[stable(feature = "rust1", since = "1.0.0")]
3021#[cfg_attr(not(test), rustc_diagnostic_item = "fs_remove_file")]
3022pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
3023    fs_imp::remove_file(path.as_ref())
3024}
3025
3026/// Given a path, queries the file system to get information about a file,
3027/// directory, etc.
3028///
3029/// This function will traverse symbolic links to query information about the
3030/// destination file. To query metadata about the path itself without following
3031/// symbolic links, use [`symlink_metadata`].
3032///
3033/// # Platform-specific behavior
3034///
3035/// This function currently corresponds to the `stat` function on Unix
3036/// and the `GetFileInformationByHandle` function on Windows.
3037/// Note that, this [may change in the future][changes].
3038///
3039/// [changes]: io#platform-specific-behavior
3040///
3041/// # Errors
3042///
3043/// This function will return an error in the following situations, but is not
3044/// limited to just these cases:
3045///
3046/// * The user lacks permissions to perform `metadata` call on `path`.
3047/// * `path` does not exist.
3048/// * `path` is a symbolic link, but the destination file cannot be resolved.
3049///
3050/// # Examples
3051///
3052/// ```rust,no_run
3053/// use std::fs;
3054///
3055/// fn main() -> std::io::Result<()> {
3056///     let attr = fs::metadata("/some/file/path.txt")?;
3057///     // inspect attr ...
3058///     Ok(())
3059/// }
3060/// ```
3061#[doc(alias = "stat", alias = "GetFileAttributes", alias = "GetFileAttributesEx")]
3062#[stable(feature = "rust1", since = "1.0.0")]
3063#[cfg_attr(not(test), rustc_diagnostic_item = "fs_metadata")]
3064pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
3065    fs_imp::metadata(path.as_ref()).map(Metadata)
3066}
3067
3068/// Queries the metadata about a file without following symlinks.
3069///
3070/// This function will return the [`Metadata`] of the exact path without
3071/// traversing symbolic links to a resolved destination file. Using this function
3072/// on a path that is a file or directory (not a symbolic link) will behave the
3073/// same as [`metadata`].
3074///
3075/// # Platform-specific behavior
3076///
3077/// This function currently corresponds to the `lstat` function on Unix
3078/// and the `GetFileInformationByHandle` function on Windows.
3079/// Note that, this [may change in the future][changes].
3080///
3081/// [changes]: io#platform-specific-behavior
3082///
3083/// # Errors
3084///
3085/// This function will return an error in the following situations, but is not
3086/// limited to just these cases:
3087///
3088/// * The user lacks permissions to perform `metadata` call on `path`.
3089/// * `path` does not exist.
3090///
3091/// # Examples
3092///
3093/// ```rust,no_run
3094/// use std::fs;
3095///
3096/// fn main() -> std::io::Result<()> {
3097///     let attr = fs::symlink_metadata("/some/file/path.txt")?;
3098///     // inspect attr ...
3099///     Ok(())
3100/// }
3101/// ```
3102#[doc(alias = "lstat", alias = "GetFileAttributes", alias = "GetFileAttributesEx")]
3103#[stable(feature = "symlink_metadata", since = "1.1.0")]
3104#[cfg_attr(not(test), rustc_diagnostic_item = "fs_symlink_metadata")]
3105pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
3106    fs_imp::symlink_metadata(path.as_ref()).map(Metadata)
3107}
3108
3109/// Renames a file or directory to a new name, replacing the original file if
3110/// `to` already exists.
3111///
3112/// This will not work if the new name is on a different mount point.
3113///
3114/// # Platform-specific behavior
3115///
3116/// This function currently corresponds to the [rename] function on Unix, and
3117/// `MoveFileExW` with a fallback to `SetFileInformationByHandle` on Windows.
3118/// The exact behavior differs:
3119///
3120/// - If `to` does not exist, `from` can be anything.
3121/// - On Unix, when `from` is a directory and `to` exists, `to` must be an empty directory.
3122/// - On Unix, when `from` is not a directory and `to` exists, `to` may not be a directory.
3123/// - On Windows 10 version 1607 and above, the behavior is the same as Unix if the
3124///   filesystem supports  `FileRenameInfoEx`.
3125/// - Otherwise on Windows, `from` can be anything but `to` must not be a directory.
3126///
3127/// Note that, this [may change in the future][changes].
3128///
3129/// [changes]: io#platform-specific-behavior
3130/// [rename]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/rename.html
3131///
3132/// # Errors
3133///
3134/// This function will return an error in the following situations, but is not
3135/// limited to just these cases:
3136///
3137/// * `from` does not exist.
3138/// * The user lacks permissions to view contents.
3139/// * `from` and `to` are on separate filesystems.
3140///
3141/// # Examples
3142///
3143/// ```no_run
3144/// use std::fs;
3145///
3146/// fn main() -> std::io::Result<()> {
3147///     fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
3148///     Ok(())
3149/// }
3150/// ```
3151#[doc(alias = "mv", alias = "MoveFile", alias = "MoveFileEx")]
3152#[stable(feature = "rust1", since = "1.0.0")]
3153#[cfg_attr(not(test), rustc_diagnostic_item = "fs_rename")]
3154pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
3155    fs_imp::rename(from.as_ref(), to.as_ref())
3156}
3157
3158/// Renames a file or directory to a new name, returning [`AlreadyExists`] if `to` already
3159/// exists.
3160///
3161/// Unlike [`fs::rename`], the destination is never overwritten. The check happens as part of the
3162/// same operation, which avoids check-then-rename races.
3163///
3164/// If the system crashes in the middle, it may be possible to end up with both copies of the file
3165/// existing, but it should not be possible to end up with zero copies, or with a half-written file.
3166///
3167/// This will not work if the new name is on a different mount point.
3168///
3169/// # Platform-specific behavior
3170///
3171/// This function currently corresponds to:
3172///
3173/// * [renameat2] with `RENAME_NOREPLACE` on Linux and Android
3174/// * `renamex_np` with `RENAME_EXCL` on Apple platforms
3175/// * [MoveFileExW] without the `MOVEFILE_REPLACE_EXISTING` flag, with a fallback to
3176///   `SetFileInformationByHandle`, on Windows
3177/// * `link` followed by `unlink` on other Unix platforms and on WASI
3178/// * Otherwise, this function returns [`Unsupported`]
3179///
3180/// The `link` and `unlink` fallback is also used at runtime on Linux, Android and Apple platforms
3181/// when the kernel or the filesystem does not support the flag, so which of these applies can
3182/// differ between filesystems on the same machine.
3183///
3184/// Note that, this [may change in the future][changes].
3185///
3186/// [changes]: io#platform-specific-behavior
3187/// [renameat2]: https://man7.org/linux/man-pages/man2/renameat2.2.html
3188/// [MoveFileExW]: https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw
3189/// [`AlreadyExists`]: crate::io::ErrorKind::AlreadyExists
3190/// [`Unsupported`]: crate::io::ErrorKind::Unsupported
3191/// [`fs::rename`]: crate::fs::rename
3192///
3193/// # Errors
3194///
3195/// This function will return an error in the following situations, but is not
3196/// limited to just these cases:
3197///
3198/// * `from` does not exist.
3199/// * The user lacks permissions to view contents.
3200/// * `from` and `to` are on separate filesystems.
3201/// * `to` already exists.
3202/// * The platform does not support this operation.
3203///
3204/// # Examples
3205///
3206/// ```no_run
3207/// #![feature(rename_noreplace)]
3208/// use std::fs;
3209/// use std::io::ErrorKind;
3210///
3211/// fn main() -> std::io::Result<()> {
3212///     // Renames a.txt to b.txt, b.txt does not exist yet.
3213///     fs::rename_noreplace("a.txt", "b.txt")?;
3214///
3215///     // b.txt exists now, so this fails instead of silently overwriting it.
3216///     let err = fs::rename_noreplace("c.txt", "b.txt").unwrap_err();
3217///     assert_eq!(err.kind(), ErrorKind::AlreadyExists);
3218///     Ok(())
3219/// }
3220/// ```
3221#[doc(alias = "renameat2", alias = "renamex_np", alias = "MoveFileEx", alias = "RENAME_NOREPLACE")]
3222#[unstable(feature = "rename_noreplace", issue = "161427")]
3223#[cfg_attr(not(test), rustc_diagnostic_item = "fs_rename_noreplace")]
3224pub fn rename_noreplace<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
3225    fs_imp::rename_noreplace(from.as_ref(), to.as_ref())
3226}
3227
3228/// Copies the contents of one file to another. This function will also
3229/// copy the permission bits of the original file to the destination file.
3230///
3231/// This function will **overwrite** the contents of `to`.
3232///
3233/// Note that if `from` and `to` both point to the same file, then the file
3234/// will likely get truncated by this operation.
3235///
3236/// On success, the total number of bytes copied is returned and it is equal to
3237/// the length of the `to` file as reported by `metadata`.
3238///
3239/// If you want to copy the contents of one file to another and you’re
3240/// working with [`File`]s, see the [`io::copy`](io::copy()) function.
3241///
3242/// # Platform-specific behavior
3243///
3244/// This function currently corresponds to the `open` function in Unix
3245/// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
3246/// `O_CLOEXEC` is set for returned file descriptors.
3247///
3248/// On Linux (including Android), this function uses copy_file_range(2),
3249/// sendfile(2), or splice(2) syscalls to move data directly between files
3250/// if possible.
3251///
3252/// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
3253/// NTFS streams are copied but only the size of the main stream is returned by
3254/// this function.
3255///
3256/// On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`.
3257///
3258/// Note that platform-specific behavior [may change in the future][changes].
3259///
3260/// [changes]: io#platform-specific-behavior
3261///
3262/// # Errors
3263///
3264/// This function will return an error in the following situations, but is not
3265/// limited to just these cases:
3266///
3267/// * `from` is neither a regular file nor a symlink to a regular file.
3268/// * `from` does not exist.
3269/// * The current process does not have the permission rights to read
3270///   `from` or write `to`.
3271/// * The parent directory of `to` doesn't exist.
3272///
3273/// # Examples
3274///
3275/// ```no_run
3276/// use std::fs;
3277///
3278/// fn main() -> std::io::Result<()> {
3279///     fs::copy("foo.txt", "bar.txt")?;  // Copy foo.txt to bar.txt
3280///     Ok(())
3281/// }
3282/// ```
3283#[doc(alias = "cp")]
3284#[doc(alias = "copy_file_range")]
3285#[doc(alias = "CopyFile", alias = "CopyFileEx")]
3286#[doc(alias = "fclonefileat", alias = "fcopyfile")]
3287#[stable(feature = "rust1", since = "1.0.0")]
3288#[cfg_attr(not(test), rustc_diagnostic_item = "fs_copy")]
3289pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
3290    fs_imp::copy(from.as_ref(), to.as_ref())
3291}
3292
3293/// Creates a new hard link on the filesystem.
3294///
3295/// The `link` path will be a link pointing to the `original` path. Note that
3296/// systems often require these two paths to both be located on the same
3297/// filesystem.
3298///
3299/// If `original` names a symbolic link, it is platform-specific whether the
3300/// symbolic link is followed. On platforms where it's possible to not follow
3301/// it, it is not followed, and the created hard link points to the symbolic
3302/// link itself.
3303///
3304/// # Platform-specific behavior
3305///
3306/// This function currently corresponds to the `CreateHardLink` function on Windows.
3307/// On most Unix systems, it corresponds to the `linkat` function with no flags.
3308/// On VxWorks and Redox, it instead corresponds to the `link` function.
3309/// On MacOS, it uses the `linkat` function if it is available, but on very old
3310/// systems where `linkat` is not available, `link` is selected at runtime instead.
3311/// Note that, this [may change in the future][changes].
3312///
3313/// [changes]: io#platform-specific-behavior
3314///
3315/// # Errors
3316///
3317/// This function will return an error in the following situations, but is not
3318/// limited to just these cases:
3319///
3320/// * The `original` path is not a file or doesn't exist.
3321/// * The 'link' path already exists.
3322///
3323/// # Examples
3324///
3325/// ```no_run
3326/// use std::fs;
3327///
3328/// fn main() -> std::io::Result<()> {
3329///     fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
3330///     Ok(())
3331/// }
3332/// ```
3333#[doc(alias = "CreateHardLink", alias = "linkat")]
3334#[stable(feature = "rust1", since = "1.0.0")]
3335#[cfg_attr(not(test), rustc_diagnostic_item = "fs_hard_link")]
3336pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
3337    fs_imp::hard_link(original.as_ref(), link.as_ref())
3338}
3339
3340/// Creates a new symbolic link on the filesystem.
3341///
3342/// The `link` path will be a symbolic link pointing to the `original` path.
3343/// On Windows, this will be a file symlink, not a directory symlink;
3344/// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
3345/// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
3346/// used instead to make the intent explicit.
3347///
3348/// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
3349/// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
3350/// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
3351///
3352/// # Examples
3353///
3354/// ```no_run
3355/// use std::fs;
3356///
3357/// fn main() -> std::io::Result<()> {
3358///     fs::soft_link("a.txt", "b.txt")?;
3359///     Ok(())
3360/// }
3361/// ```
3362#[stable(feature = "rust1", since = "1.0.0")]
3363#[deprecated(
3364    since = "1.1.0",
3365    note = "replaced with std::os::unix::fs::symlink and \
3366            std::os::windows::fs::{symlink_file, symlink_dir}"
3367)]
3368pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
3369    fs_imp::symlink(original.as_ref(), link.as_ref())
3370}
3371
3372/// Reads a symbolic link, returning the file that the link points to.
3373///
3374/// # Platform-specific behavior
3375///
3376/// This function currently corresponds to the `readlink` function on Unix
3377/// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
3378/// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
3379/// Note that, this [may change in the future][changes].
3380///
3381/// [changes]: io#platform-specific-behavior
3382///
3383/// # Errors
3384///
3385/// This function will return an error in the following situations, but is not
3386/// limited to just these cases:
3387///
3388/// * `path` is not a symbolic link.
3389/// * `path` does not exist.
3390///
3391/// # Examples
3392///
3393/// ```no_run
3394/// use std::fs;
3395///
3396/// fn main() -> std::io::Result<()> {
3397///     let path = fs::read_link("a.txt")?;
3398///     Ok(())
3399/// }
3400/// ```
3401#[stable(feature = "rust1", since = "1.0.0")]
3402#[cfg_attr(not(test), rustc_diagnostic_item = "fs_read_link")]
3403pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
3404    fs_imp::read_link(path.as_ref())
3405}
3406
3407/// Returns the canonical, absolute form of a path with all intermediate
3408/// components normalized and symbolic links resolved.
3409///
3410/// # Platform-specific behavior
3411///
3412/// This function currently corresponds to the `realpath` function on Unix
3413/// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
3414/// Note that this [may change in the future][changes].
3415///
3416/// On Windows, this converts the path to use [extended length path][path]
3417/// syntax, which allows your program to use longer path names, but means you
3418/// can only join backslash-delimited paths to it, and it may be incompatible
3419/// with other applications (if passed to the application on the command-line,
3420/// or written to a file another application may read).
3421///
3422/// [changes]: io#platform-specific-behavior
3423/// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
3424///
3425/// # Errors
3426///
3427/// This function will return an error in the following situations, but is not
3428/// limited to just these cases:
3429///
3430/// * `path` does not exist.
3431/// * A non-final component in path is not a directory.
3432///
3433/// # Examples
3434///
3435/// ```no_run
3436/// use std::fs;
3437///
3438/// fn main() -> std::io::Result<()> {
3439///     let path = fs::canonicalize("../a/../foo.txt")?;
3440///     Ok(())
3441/// }
3442/// ```
3443#[doc(alias = "realpath")]
3444#[doc(alias = "GetFinalPathNameByHandle")]
3445#[stable(feature = "fs_canonicalize", since = "1.5.0")]
3446#[cfg_attr(not(test), rustc_diagnostic_item = "fs_canonicalize")]
3447pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
3448    fs_imp::canonicalize(path.as_ref())
3449}
3450
3451/// Creates a new, empty directory at the provided path.
3452///
3453/// # Platform-specific behavior
3454///
3455/// This function currently corresponds to the `mkdir` function on Unix
3456/// and the `CreateDirectoryW` function on Windows.
3457/// Note that, this [may change in the future][changes].
3458///
3459/// [changes]: io#platform-specific-behavior
3460///
3461/// **NOTE**: If a parent of the given path doesn't exist, this function will
3462/// return an error. To create a directory and all its missing parents at the
3463/// same time, use the [`create_dir_all`] function.
3464///
3465/// # Errors
3466///
3467/// This function will return an error in the following situations, but is not
3468/// limited to just these cases:
3469///
3470/// * User lacks permissions to create directory at `path`.
3471/// * A parent of the given path doesn't exist. (To create a directory and all
3472///   its missing parents at the same time, use the [`create_dir_all`]
3473///   function.)
3474/// * `path` already exists.
3475///
3476/// # Examples
3477///
3478/// ```no_run
3479/// use std::fs;
3480///
3481/// fn main() -> std::io::Result<()> {
3482///     fs::create_dir("/some/dir")?;
3483///     Ok(())
3484/// }
3485/// ```
3486#[doc(alias = "mkdir", alias = "CreateDirectory")]
3487#[stable(feature = "rust1", since = "1.0.0")]
3488#[cfg_attr(not(test), rustc_diagnostic_item = "fs_create_dir")]
3489pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
3490    DirBuilder::new().create(path.as_ref())
3491}
3492
3493/// Recursively create a directory and all of its parent components if they
3494/// are missing.
3495///
3496/// This function is not atomic. If it returns an error, any parent components it was able to create
3497/// will remain.
3498///
3499/// If the empty path is passed to this function, it always succeeds without
3500/// creating any directories.
3501///
3502/// # Platform-specific behavior
3503///
3504/// This function currently corresponds to multiple calls to the `mkdir`
3505/// function on Unix and the `CreateDirectoryW` function on Windows.
3506///
3507/// Note that, this [may change in the future][changes].
3508///
3509/// [changes]: io#platform-specific-behavior
3510///
3511/// # Errors
3512///
3513/// The function will return an error if any directory specified in path does not exist and
3514/// could not be created. There may be other error conditions; see [`fs::create_dir`] for specifics.
3515///
3516/// Notable exception is made for situations where any of the directories
3517/// specified in the `path` could not be created as it was being created concurrently.
3518/// Such cases are considered to be successful. That is, calling `create_dir_all`
3519/// concurrently from multiple threads or processes is guaranteed not to fail
3520/// due to a race condition with itself.
3521///
3522/// [`fs::create_dir`]: create_dir
3523///
3524/// # Examples
3525///
3526/// ```no_run
3527/// use std::fs;
3528///
3529/// fn main() -> std::io::Result<()> {
3530///     fs::create_dir_all("/some/dir")?;
3531///     Ok(())
3532/// }
3533/// ```
3534#[doc(alias = "mkdir", alias = "CreateDirectory")]
3535#[stable(feature = "rust1", since = "1.0.0")]
3536#[cfg_attr(not(test), rustc_diagnostic_item = "fs_create_dir_all")]
3537pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
3538    DirBuilder::new().recursive(true).create(path.as_ref())
3539}
3540
3541/// Removes an empty directory.
3542///
3543/// If you want to remove a directory that is not empty, as well as all
3544/// of its contents recursively, consider using [`remove_dir_all`]
3545/// instead.
3546///
3547/// # Platform-specific behavior
3548///
3549/// This function currently corresponds to the `rmdir` function on Unix
3550/// and the `RemoveDirectory` function on Windows.
3551/// Note that, this [may change in the future][changes].
3552///
3553/// On Windows, this can also be used to remove symbolic links to directories.
3554/// On Unix, [`remove_file`] must be used for that purpose.
3555///
3556/// [changes]: io#platform-specific-behavior
3557///
3558/// # Errors
3559///
3560/// This function will return an error in the following situations, but is not
3561/// limited to just these cases:
3562///
3563/// * `path` doesn't exist.
3564/// * `path` isn't a directory.
3565/// * The user lacks permissions to remove the directory at the provided `path`.
3566/// * The directory isn't empty.
3567///
3568/// This function will only ever return an error of kind `NotFound` if the given
3569/// path does not exist. Note that the inverse is not true,
3570/// i.e. if a path does not exist, its removal may fail for a number of reasons,
3571/// such as insufficient permissions.
3572///
3573/// # Examples
3574///
3575/// ```no_run
3576/// use std::fs;
3577///
3578/// fn main() -> std::io::Result<()> {
3579///     fs::remove_dir("/some/dir")?;
3580///     Ok(())
3581/// }
3582/// ```
3583#[doc(alias = "rmdir", alias = "RemoveDirectory")]
3584#[stable(feature = "rust1", since = "1.0.0")]
3585#[cfg_attr(not(test), rustc_diagnostic_item = "fs_remove_dir")]
3586pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
3587    fs_imp::remove_dir(path.as_ref())
3588}
3589
3590/// Removes a directory at this path, after removing all its contents. Use
3591/// carefully!
3592///
3593/// This function does **not** follow symbolic links and it will simply remove the
3594/// symbolic link itself. If `path` itself is a symbolic link to a directory, it will get
3595/// removed. If it is a symbolic link to a file, behavior is platform-specific:
3596/// currently, it will get removed on Unix-like systems but not on Windows.
3597///
3598/// # Platform-specific behavior
3599///
3600/// These implementation details [may change in the future][changes].
3601///
3602/// - "Unix-like": By default, this function currently corresponds to
3603/// `openat`, `fdopendir`, `unlinkat` and `lstat`
3604/// on Unix-family platforms, except where noted otherwise.
3605/// - "Windows": This function currently corresponds to `CreateFileW`,
3606/// `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile`.
3607///
3608/// ## Time-of-check to time-of-use (TOCTOU) race conditions
3609/// See the [module-level TOCTOU explanation](self#time-of-check-to-time-of-use-toctou).
3610///
3611/// On most platforms, `fs::remove_dir_all` protects against symlink TOCTOU races by default.
3612/// However, on the following platforms, this protection is not provided and the function should
3613/// not be used in security-sensitive contexts:
3614/// - **Miri**: Even when emulating targets where the underlying implementation will protect against
3615///   TOCTOU races, Miri will not do so.
3616/// - **ESP-IDF**, **Horizon**, **PS Vita**, **QNX**, **Redox OS**, **VxWorks**: This function does
3617///   not protect against TOCTOU races, as the underlying platform does not implement the required
3618///   platform support to do so.
3619///
3620/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
3621/// [changes]: io#platform-specific-behavior
3622///
3623/// # Errors
3624///
3625/// See [`fs::remove_file`] and [`fs::remove_dir`].
3626///
3627/// [`remove_dir_all`] will fail if [`remove_dir`] or [`remove_file`] fail on *any* constituent
3628/// paths, *including* the root `path`. Consequently,
3629///
3630/// - The directory you are deleting *must* exist, meaning that this function is *not idempotent*.
3631/// - [`remove_dir_all`] will fail if the `path` is *not* a directory.
3632///
3633/// Consider ignoring the error if validating the removal is not required for your use case.
3634///
3635/// This function may return [`io::ErrorKind::DirectoryNotEmpty`] if the directory is concurrently
3636/// written into, which typically indicates some contents were removed but not all.
3637/// [`io::ErrorKind::NotFound`] is only returned if no removal occurs.
3638///
3639/// [`fs::remove_file`]: remove_file
3640/// [`fs::remove_dir`]: remove_dir
3641///
3642/// # Examples
3643///
3644/// ```no_run
3645/// use std::fs;
3646///
3647/// fn main() -> std::io::Result<()> {
3648///     fs::remove_dir_all("/some/dir")?;
3649///     Ok(())
3650/// }
3651/// ```
3652#[doc(alias = "rm")]
3653#[stable(feature = "rust1", since = "1.0.0")]
3654#[cfg_attr(not(test), rustc_diagnostic_item = "fs_remove_dir_all")]
3655pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
3656    fs_imp::remove_dir_all(path.as_ref())
3657}
3658
3659/// Returns an iterator over the entries within a directory.
3660///
3661/// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
3662/// New errors may be encountered after an iterator is initially constructed.
3663/// Entries for the current and parent directories (typically `.` and `..`) are
3664/// skipped.
3665///
3666/// The order in which `read_dir` returns entries can change between calls. If reproducible
3667/// ordering is required, the entries should be explicitly sorted.
3668///
3669/// # Platform-specific behavior
3670///
3671/// This function currently corresponds to the `opendir` function on Unix
3672/// and the `FindFirstFileEx` function on Windows. Advancing the iterator
3673/// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
3674/// Note that, this [may change in the future][changes].
3675///
3676/// [changes]: io#platform-specific-behavior
3677///
3678/// The order in which this iterator returns entries is platform and filesystem
3679/// dependent.
3680///
3681/// # Errors
3682///
3683/// This function will return an error in the following situations, but is not
3684/// limited to just these cases:
3685///
3686/// * The provided `path` doesn't exist.
3687/// * The process lacks permissions to view the contents.
3688/// * The `path` points at a non-directory file.
3689///
3690/// # Examples
3691///
3692/// ```
3693/// use std::io;
3694/// use std::fs::{self, DirEntry};
3695/// use std::path::Path;
3696///
3697/// // one possible implementation of walking a directory only visiting files
3698/// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
3699///     if dir.is_dir() {
3700///         for entry in fs::read_dir(dir)? {
3701///             let entry = entry?;
3702///             let path = entry.path();
3703///             if path.is_dir() {
3704///                 visit_dirs(&path, cb)?;
3705///             } else {
3706///                 cb(&entry);
3707///             }
3708///         }
3709///     }
3710///     Ok(())
3711/// }
3712/// ```
3713///
3714/// ```rust,no_run
3715/// use std::{fs, io};
3716///
3717/// fn main() -> io::Result<()> {
3718///     let mut entries = fs::read_dir(".")?
3719///         .map(|res| res.map(|e| e.path()))
3720///         .collect::<Result<Vec<_>, io::Error>>()?;
3721///
3722///     // The order in which `read_dir` returns entries is not guaranteed. If reproducible
3723///     // ordering is required the entries should be explicitly sorted.
3724///
3725///     entries.sort();
3726///
3727///     // The entries have now been sorted by their path.
3728///
3729///     Ok(())
3730/// }
3731/// ```
3732#[doc(alias = "ls", alias = "opendir", alias = "FindFirstFile", alias = "FindNextFile")]
3733#[stable(feature = "rust1", since = "1.0.0")]
3734#[cfg_attr(not(test), rustc_diagnostic_item = "fs_read_dir")]
3735pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
3736    fs_imp::read_dir(path.as_ref()).map(ReadDir)
3737}
3738
3739/// Changes the permissions found on a file or a directory.
3740///
3741/// # Platform-specific behavior
3742///
3743/// This function currently corresponds to the `chmod` function on Unix
3744/// and the `SetFileAttributes` function on Windows.
3745/// Note that, this [may change in the future][changes].
3746///
3747/// [changes]: io#platform-specific-behavior
3748///
3749/// ## Symlinks
3750/// On UNIX-like systems, this function will update the permission bits
3751/// of the file pointed to by the symlink.
3752///
3753/// Note that this behavior can lead to privilege escalation vulnerabilities,
3754/// where the ability to create a symlink in one directory allows you to
3755/// cause the permissions of another file or directory to be modified.
3756///
3757/// For this reason, using this function with symlinks should be avoided.
3758/// When possible, permissions should be set at creation time instead.
3759///
3760/// # Rationale
3761/// POSIX does not specify an `lchmod` function,
3762/// and symlinks can be followed regardless of what permission bits are set.
3763///
3764/// # Errors
3765///
3766/// This function will return an error in the following situations, but is not
3767/// limited to just these cases:
3768///
3769/// * `path` does not exist.
3770/// * The user lacks the permission to change attributes of the file.
3771///
3772/// # Examples
3773///
3774/// ```no_run
3775/// use std::fs;
3776///
3777/// fn main() -> std::io::Result<()> {
3778///     let mut perms = fs::metadata("foo.txt")?.permissions();
3779///     perms.set_readonly(true);
3780///     fs::set_permissions("foo.txt", perms)?;
3781///     Ok(())
3782/// }
3783/// ```
3784#[doc(alias = "chmod", alias = "SetFileAttributes")]
3785#[stable(feature = "set_permissions", since = "1.1.0")]
3786#[cfg_attr(not(test), rustc_diagnostic_item = "fs_set_permissions")]
3787pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
3788    fs_imp::set_permissions(path.as_ref(), perm.0)
3789}
3790
3791/// Changes the permissions found on a file or a directory. On certain platforms, if the file
3792/// is a symlink, it will change the permissions bits on the symlink itself rather than
3793/// the target (e.g. Windows, BSD, MacOS). On other platforms, this results in an error when
3794/// attempting to change permissions on a symlink (e.g. Linux).
3795///
3796/// Note that non-final path elements are allowed to be symlinks.
3797///
3798/// # Platform-specific behavior
3799///
3800/// This function currently corresponds to the following underlying operations:
3801/// * Android: returns [`Unsupported`] on all files.
3802/// * Linux, BSD-based platforms, QNX, NTO: `fchmodat` with `AT_SYMLINK_NOFOLLOW`.
3803///   If that is not supported, we fall back to:
3804///   * Unix-based platforms with symlinks: `open` with `O_NOFOLLOW` followed by
3805///   [`fs::set_permissions`].
3806///   * Unix-based platforms without symlinks: `open` followed by [`fs::set_permissions`].
3807/// * Windows: `CreateFileW` with `FILE_FLAG_OPEN_REPARSE_POINT` followed
3808///   by `SetFileInformationByHandle`.
3809///
3810/// Note that, this [may change in the future][changes].
3811///
3812/// [changes]: io#platform-specific-behavior
3813///
3814/// [`fs::set_permissions`]: crate::fs::set_permissions
3815///
3816/// # Errors
3817///
3818/// This function will return an error in the following situations, but is not
3819/// limited to just these cases:
3820///
3821/// * `path` does not exist.
3822/// * The user lacks the permission to change attributes of the file.
3823///
3824/// Note: On Linux and other Unix-based platforms with symlinks (non-BSD-based),
3825/// this will result in an [`Unsupported`] error if the final element is a symlink.
3826///
3827/// [`Unsupported`]: crate::io::ErrorKind::Unsupported
3828///
3829/// # Examples
3830///
3831/// ```no_run
3832/// #![feature(set_permissions_nofollow)]
3833/// use std::fs;
3834///
3835/// fn main() -> std::io::Result<()> {
3836///     let mut perms = fs::symlink_metadata("foo.txt")?.permissions();
3837///     perms.set_readonly(true);
3838///     // This should result in an error on certain platforms or
3839///     // succeed in modifying the permissions of a symlink
3840///     fs::set_permissions_nofollow("foo.txt", perms)?;
3841///     Ok(())
3842/// }
3843/// ```
3844#[doc(alias = "fchmodat", alias = "SetFileInformationByHandle")]
3845#[unstable(feature = "set_permissions_nofollow", issue = "141607")]
3846#[cfg_attr(not(test), rustc_diagnostic_item = "fs_set_permissions_nofollow")]
3847pub fn set_permissions_nofollow<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
3848    fs_imp::set_permissions_nofollow(path.as_ref(), perm.0)
3849}
3850
3851impl DirBuilder {
3852    /// Creates a new set of options with default mode/security settings for all
3853    /// platforms and also non-recursive.
3854    ///
3855    /// # Examples
3856    ///
3857    /// ```
3858    /// use std::fs::DirBuilder;
3859    ///
3860    /// let builder = DirBuilder::new();
3861    /// ```
3862    #[stable(feature = "dir_builder", since = "1.6.0")]
3863    #[must_use]
3864    pub fn new() -> DirBuilder {
3865        DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
3866    }
3867
3868    /// Indicates that directories should be created recursively, creating all
3869    /// parent directories. Parents that do not exist are created with the same
3870    /// security and permissions settings.
3871    ///
3872    /// This option defaults to `false`.
3873    ///
3874    /// # Examples
3875    ///
3876    /// ```
3877    /// use std::fs::DirBuilder;
3878    ///
3879    /// let mut builder = DirBuilder::new();
3880    /// builder.recursive(true);
3881    /// ```
3882    #[stable(feature = "dir_builder", since = "1.6.0")]
3883    pub fn recursive(&mut self, recursive: bool) -> &mut Self {
3884        self.recursive = recursive;
3885        self
3886    }
3887
3888    /// Creates the specified directory with the options configured in this
3889    /// builder.
3890    ///
3891    /// It is considered an error if the directory already exists unless
3892    /// recursive mode is enabled.
3893    ///
3894    /// # Examples
3895    ///
3896    /// ```no_run
3897    /// use std::fs::{self, DirBuilder};
3898    ///
3899    /// let path = "/tmp/foo/bar/baz";
3900    /// DirBuilder::new()
3901    ///     .recursive(true)
3902    ///     .create(path).unwrap();
3903    ///
3904    /// assert!(fs::metadata(path).unwrap().is_dir());
3905    /// ```
3906    #[stable(feature = "dir_builder", since = "1.6.0")]
3907    pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
3908        self._create(path.as_ref())
3909    }
3910
3911    fn _create(&self, path: &Path) -> io::Result<()> {
3912        if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
3913    }
3914
3915    fn create_dir_all(&self, path: &Path) -> io::Result<()> {
3916        // if path's parent is None, it is "/" path, which should
3917        // return Ok immediately
3918        if path.is_empty() || path.parent().is_none() {
3919            return Ok(());
3920        }
3921
3922        // For certain platforms, a path like "/tmp/foo/.", while the "/tmp" directory exists,
3923        // the mkdir function may produce a `NotFound` error on that path instead of succeeding
3924        // due to viewing the "foo" and "." as two separate missing components.
3925        // See https://github.com/rust-lang/rust/issues/162243
3926        let path = path.components().as_path();
3927        let ancestors = path.ancestors();
3928        let mut uncreated_dirs = 0;
3929
3930        for ancestor in ancestors {
3931            // for relative paths like "foo/bar", the parent of
3932            // "foo" will be "" which there's no need to invoke
3933            // a mkdir syscall on
3934            if ancestor.is_empty() || ancestor.parent().is_none() {
3935                break;
3936            }
3937
3938            match self.inner.mkdir(ancestor) {
3939                Ok(()) => break,
3940                Err(e) if e.kind() == io::ErrorKind::NotFound => uncreated_dirs += 1,
3941                // we check if the err is AlreadyExists for two reasons
3942                //    - in case the path exists as a *file*
3943                //    - and to avoid calls to .is_dir() in case of other errs
3944                //      (i.e. PermissionDenied)
3945                Err(e) if e.kind() == io::ErrorKind::AlreadyExists && ancestor.is_dir() => break,
3946                Err(e) => return Err(e),
3947            }
3948        }
3949
3950        // collect only the uncreated directories w/o letting the vec resize
3951        let mut uncreated_dirs_vec = Vec::with_capacity(uncreated_dirs);
3952        uncreated_dirs_vec.extend(ancestors.take(uncreated_dirs));
3953
3954        for uncreated_dir in uncreated_dirs_vec.iter().rev() {
3955            if let Err(e) = self.inner.mkdir(uncreated_dir) {
3956                if e.kind() != io::ErrorKind::AlreadyExists || !uncreated_dir.is_dir() {
3957                    return Err(e);
3958                }
3959            }
3960        }
3961
3962        Ok(())
3963    }
3964}
3965
3966impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
3967    #[inline]
3968    fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
3969        &mut self.inner
3970    }
3971}
3972
3973/// Returns `Ok(true)` if the path points at an existing entity.
3974///
3975/// This function will traverse symbolic links to query information about the
3976/// destination file. In case of broken symbolic links this will return `Ok(false)`.
3977///
3978/// As opposed to the [`Path::exists`] method, this will only return `Ok(true)` or `Ok(false)`
3979/// if the path was _verified_ to exist or not exist. If its existence can neither be confirmed
3980/// nor denied, an `Err(_)` will be propagated instead. This can be the case if e.g. listing
3981/// permission is denied on one of the parent directories.
3982///
3983/// Note that while this avoids some pitfalls of the `exists()` method, it still can not
3984/// prevent time-of-check to time-of-use ([TOCTOU]) bugs. You should only use it in scenarios
3985/// where those bugs are not an issue.
3986///
3987/// # Examples
3988///
3989/// ```no_run
3990/// use std::fs;
3991///
3992/// assert!(!fs::exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
3993/// assert!(fs::exists("/root/secret_file.txt").is_err());
3994/// ```
3995///
3996/// [`Path::exists`]: crate::path::Path::exists
3997/// [TOCTOU]: self#time-of-check-to-time-of-use-toctou
3998#[stable(feature = "fs_try_exists", since = "1.81.0")]
3999#[cfg_attr(not(test), rustc_diagnostic_item = "fs_exists")]
4000#[inline]
4001pub fn exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
4002    fs_imp::exists(path.as_ref())
4003}