Skip to main content

std/
fs.rs

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