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