[go: up one dir, main page]

std/
fs.rs

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