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