]> git.lizzy.rs Git - rust.git/blob - library/std/src/fs.rs
Auto merge of #95678 - pietroalbini:pa-1.62.0-bootstrap, r=Mark-Simulacrum
[rust.git] / library / std / src / 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(test, not(any(target_os = "emscripten", target_env = "sgx"))))]
12 mod tests;
13
14 use crate::ffi::OsString;
15 use crate::fmt;
16 use crate::io::{self, IoSlice, IoSliceMut, Read, ReadBuf, Seek, SeekFrom, Write};
17 use crate::path::{Path, PathBuf};
18 use crate::sys::fs as fs_imp;
19 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
20 use crate::time::SystemTime;
21
22 /// A reference to an open file on the filesystem.
23 ///
24 /// An instance of a `File` can be read and/or written depending on what options
25 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
26 /// that the file contains internally.
27 ///
28 /// Files are automatically closed when they go out of scope.  Errors detected
29 /// on closing are ignored by the implementation of `Drop`.  Use the method
30 /// [`sync_all`] if these errors must be manually handled.
31 ///
32 /// # Examples
33 ///
34 /// Creates a new file and write bytes to it (you can also use [`write()`]):
35 ///
36 /// ```no_run
37 /// use std::fs::File;
38 /// use std::io::prelude::*;
39 ///
40 /// fn main() -> std::io::Result<()> {
41 ///     let mut file = File::create("foo.txt")?;
42 ///     file.write_all(b"Hello, world!")?;
43 ///     Ok(())
44 /// }
45 /// ```
46 ///
47 /// Read the contents of a file into a [`String`] (you can also use [`read`]):
48 ///
49 /// ```no_run
50 /// use std::fs::File;
51 /// use std::io::prelude::*;
52 ///
53 /// fn main() -> std::io::Result<()> {
54 ///     let mut file = File::open("foo.txt")?;
55 ///     let mut contents = String::new();
56 ///     file.read_to_string(&mut contents)?;
57 ///     assert_eq!(contents, "Hello, world!");
58 ///     Ok(())
59 /// }
60 /// ```
61 ///
62 /// It can be more efficient to read the contents of a file with a buffered
63 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
64 ///
65 /// ```no_run
66 /// use std::fs::File;
67 /// use std::io::BufReader;
68 /// use std::io::prelude::*;
69 ///
70 /// fn main() -> std::io::Result<()> {
71 ///     let file = File::open("foo.txt")?;
72 ///     let mut buf_reader = BufReader::new(file);
73 ///     let mut contents = String::new();
74 ///     buf_reader.read_to_string(&mut contents)?;
75 ///     assert_eq!(contents, "Hello, world!");
76 ///     Ok(())
77 /// }
78 /// ```
79 ///
80 /// Note that, although read and write methods require a `&mut File`, because
81 /// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
82 /// still modify the file, either through methods that take `&File` or by
83 /// retrieving the underlying OS object and modifying the file that way.
84 /// Additionally, many operating systems allow concurrent modification of files
85 /// by different processes. Avoid assuming that holding a `&File` means that the
86 /// file will not change.
87 ///
88 /// # Platform-specific behavior
89 ///
90 /// On Windows, the implementation of [`Read`] and [`Write`] traits for `File`
91 /// perform synchronous I/O operations. Therefore the underlying file must not
92 /// have been opened for asynchronous I/O (e.g. by using `FILE_FLAG_OVERLAPPED`).
93 ///
94 /// [`BufReader<R>`]: io::BufReader
95 /// [`sync_all`]: File::sync_all
96 #[stable(feature = "rust1", since = "1.0.0")]
97 #[cfg_attr(not(test), rustc_diagnostic_item = "File")]
98 pub struct File {
99     inner: fs_imp::File,
100 }
101
102 /// Metadata information about a file.
103 ///
104 /// This structure is returned from the [`metadata`] or
105 /// [`symlink_metadata`] function or method and represents known
106 /// metadata about a file such as its permissions, size, modification
107 /// times, etc.
108 #[stable(feature = "rust1", since = "1.0.0")]
109 #[derive(Clone)]
110 pub struct Metadata(fs_imp::FileAttr);
111
112 /// Iterator over the entries in a directory.
113 ///
114 /// This iterator is returned from the [`read_dir`] function of this module and
115 /// will yield instances of <code>[io::Result]<[DirEntry]></code>. Through a [`DirEntry`]
116 /// information like the entry's path and possibly other metadata can be
117 /// learned.
118 ///
119 /// The order in which this iterator returns entries is platform and filesystem
120 /// dependent.
121 ///
122 /// # Errors
123 ///
124 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
125 /// IO error during iteration.
126 #[stable(feature = "rust1", since = "1.0.0")]
127 #[derive(Debug)]
128 pub struct ReadDir(fs_imp::ReadDir);
129
130 /// Entries returned by the [`ReadDir`] iterator.
131 ///
132 /// An instance of `DirEntry` represents an entry inside of a directory on the
133 /// filesystem. Each entry can be inspected via methods to learn about the full
134 /// path or possibly other metadata through per-platform extension traits.
135 #[stable(feature = "rust1", since = "1.0.0")]
136 pub struct DirEntry(fs_imp::DirEntry);
137
138 /// Options and flags which can be used to configure how a file is opened.
139 ///
140 /// This builder exposes the ability to configure how a [`File`] is opened and
141 /// what operations are permitted on the open file. The [`File::open`] and
142 /// [`File::create`] methods are aliases for commonly used options using this
143 /// builder.
144 ///
145 /// Generally speaking, when using `OpenOptions`, you'll first call
146 /// [`OpenOptions::new`], then chain calls to methods to set each option, then
147 /// call [`OpenOptions::open`], passing the path of the file you're trying to
148 /// open. This will give you a [`io::Result`] with a [`File`] inside that you
149 /// can further operate on.
150 ///
151 /// # Examples
152 ///
153 /// Opening a file to read:
154 ///
155 /// ```no_run
156 /// use std::fs::OpenOptions;
157 ///
158 /// let file = OpenOptions::new().read(true).open("foo.txt");
159 /// ```
160 ///
161 /// Opening a file for both reading and writing, as well as creating it if it
162 /// doesn't exist:
163 ///
164 /// ```no_run
165 /// use std::fs::OpenOptions;
166 ///
167 /// let file = OpenOptions::new()
168 ///             .read(true)
169 ///             .write(true)
170 ///             .create(true)
171 ///             .open("foo.txt");
172 /// ```
173 #[derive(Clone, Debug)]
174 #[stable(feature = "rust1", since = "1.0.0")]
175 pub struct OpenOptions(fs_imp::OpenOptions);
176
177 /// Representation of the various permissions on a file.
178 ///
179 /// This module only currently provides one bit of information,
180 /// [`Permissions::readonly`], which is exposed on all currently supported
181 /// platforms. Unix-specific functionality, such as mode bits, is available
182 /// through the [`PermissionsExt`] trait.
183 ///
184 /// [`PermissionsExt`]: crate::os::unix::fs::PermissionsExt
185 #[derive(Clone, PartialEq, Eq, Debug)]
186 #[stable(feature = "rust1", since = "1.0.0")]
187 pub struct Permissions(fs_imp::FilePermissions);
188
189 /// A structure representing a type of file with accessors for each file type.
190 /// It is returned by [`Metadata::file_type`] method.
191 #[stable(feature = "file_type", since = "1.1.0")]
192 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
193 #[cfg_attr(not(test), rustc_diagnostic_item = "FileType")]
194 pub struct FileType(fs_imp::FileType);
195
196 /// A builder used to create directories in various manners.
197 ///
198 /// This builder also supports platform-specific options.
199 #[stable(feature = "dir_builder", since = "1.6.0")]
200 #[cfg_attr(not(test), rustc_diagnostic_item = "DirBuilder")]
201 #[derive(Debug)]
202 pub struct DirBuilder {
203     inner: fs_imp::DirBuilder,
204     recursive: bool,
205 }
206
207 /// Read the entire contents of a file into a bytes vector.
208 ///
209 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
210 /// with fewer imports and without an intermediate variable.
211 ///
212 /// [`read_to_end`]: Read::read_to_end
213 ///
214 /// # Errors
215 ///
216 /// This function will return an error if `path` does not already exist.
217 /// Other errors may also be returned according to [`OpenOptions::open`].
218 ///
219 /// It will also return an error if it encounters while reading an error
220 /// of a kind other than [`io::ErrorKind::Interrupted`].
221 ///
222 /// # Examples
223 ///
224 /// ```no_run
225 /// use std::fs;
226 /// use std::net::SocketAddr;
227 ///
228 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
229 ///     let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
230 ///     Ok(())
231 /// }
232 /// ```
233 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
234 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
235     fn inner(path: &Path) -> io::Result<Vec<u8>> {
236         let mut file = File::open(path)?;
237         let mut bytes = Vec::new();
238         file.read_to_end(&mut bytes)?;
239         Ok(bytes)
240     }
241     inner(path.as_ref())
242 }
243
244 /// Read the entire contents of a file into a string.
245 ///
246 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
247 /// with fewer imports and without an intermediate variable.
248 ///
249 /// [`read_to_string`]: Read::read_to_string
250 ///
251 /// # Errors
252 ///
253 /// This function will return an error if `path` does not already exist.
254 /// Other errors may also be returned according to [`OpenOptions::open`].
255 ///
256 /// It will also return an error if it encounters while reading an error
257 /// of a kind other than [`io::ErrorKind::Interrupted`],
258 /// or if the contents of the file are not valid UTF-8.
259 ///
260 /// # Examples
261 ///
262 /// ```no_run
263 /// use std::fs;
264 /// use std::net::SocketAddr;
265 /// use std::error::Error;
266 ///
267 /// fn main() -> Result<(), Box<dyn Error>> {
268 ///     let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
269 ///     Ok(())
270 /// }
271 /// ```
272 #[stable(feature = "fs_read_write", since = "1.26.0")]
273 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
274     fn inner(path: &Path) -> io::Result<String> {
275         let mut file = File::open(path)?;
276         let mut string = String::new();
277         file.read_to_string(&mut string)?;
278         Ok(string)
279     }
280     inner(path.as_ref())
281 }
282
283 /// Write a slice as the entire contents of a file.
284 ///
285 /// This function will create a file if it does not exist,
286 /// and will entirely replace its contents if it does.
287 ///
288 /// This is a convenience function for using [`File::create`] and [`write_all`]
289 /// with fewer imports.
290 ///
291 /// [`write_all`]: Write::write_all
292 ///
293 /// # Examples
294 ///
295 /// ```no_run
296 /// use std::fs;
297 ///
298 /// fn main() -> std::io::Result<()> {
299 ///     fs::write("foo.txt", b"Lorem ipsum")?;
300 ///     fs::write("bar.txt", "dolor sit")?;
301 ///     Ok(())
302 /// }
303 /// ```
304 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
305 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
306     fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
307         File::create(path)?.write_all(contents)
308     }
309     inner(path.as_ref(), contents.as_ref())
310 }
311
312 impl File {
313     /// Attempts to open a file in read-only mode.
314     ///
315     /// See the [`OpenOptions::open`] method for more details.
316     ///
317     /// # Errors
318     ///
319     /// This function will return an error if `path` does not already exist.
320     /// Other errors may also be returned according to [`OpenOptions::open`].
321     ///
322     /// # Examples
323     ///
324     /// ```no_run
325     /// use std::fs::File;
326     ///
327     /// fn main() -> std::io::Result<()> {
328     ///     let mut f = File::open("foo.txt")?;
329     ///     Ok(())
330     /// }
331     /// ```
332     #[stable(feature = "rust1", since = "1.0.0")]
333     pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
334         OpenOptions::new().read(true).open(path.as_ref())
335     }
336
337     /// Opens a file in write-only mode.
338     ///
339     /// This function will create a file if it does not exist,
340     /// and will truncate it if it does.
341     ///
342     /// See the [`OpenOptions::open`] function for more details.
343     ///
344     /// # Examples
345     ///
346     /// ```no_run
347     /// use std::fs::File;
348     ///
349     /// fn main() -> std::io::Result<()> {
350     ///     let mut f = File::create("foo.txt")?;
351     ///     Ok(())
352     /// }
353     /// ```
354     #[stable(feature = "rust1", since = "1.0.0")]
355     pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
356         OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
357     }
358
359     /// Returns a new OpenOptions object.
360     ///
361     /// This function returns a new OpenOptions object that you can use to
362     /// open or create a file with specific options if `open()` or `create()`
363     /// are not appropriate.
364     ///
365     /// It is equivalent to `OpenOptions::new()`, but allows you to write more
366     /// readable code. Instead of
367     /// `OpenOptions::new().append(true).open("example.log")`,
368     /// you can write `File::options().append(true).open("example.log")`. This
369     /// also avoids the need to import `OpenOptions`.
370     ///
371     /// See the [`OpenOptions::new`] function for more details.
372     ///
373     /// # Examples
374     ///
375     /// ```no_run
376     /// use std::fs::File;
377     ///
378     /// fn main() -> std::io::Result<()> {
379     ///     let mut f = File::options().append(true).open("example.log")?;
380     ///     Ok(())
381     /// }
382     /// ```
383     #[must_use]
384     #[stable(feature = "with_options", since = "1.58.0")]
385     pub fn options() -> OpenOptions {
386         OpenOptions::new()
387     }
388
389     /// Attempts to sync all OS-internal metadata to disk.
390     ///
391     /// This function will attempt to ensure that all in-memory data reaches the
392     /// filesystem before returning.
393     ///
394     /// This can be used to handle errors that would otherwise only be caught
395     /// when the `File` is closed.  Dropping a file will ignore errors in
396     /// synchronizing this in-memory data.
397     ///
398     /// # Examples
399     ///
400     /// ```no_run
401     /// use std::fs::File;
402     /// use std::io::prelude::*;
403     ///
404     /// fn main() -> std::io::Result<()> {
405     ///     let mut f = File::create("foo.txt")?;
406     ///     f.write_all(b"Hello, world!")?;
407     ///
408     ///     f.sync_all()?;
409     ///     Ok(())
410     /// }
411     /// ```
412     #[stable(feature = "rust1", since = "1.0.0")]
413     pub fn sync_all(&self) -> io::Result<()> {
414         self.inner.fsync()
415     }
416
417     /// This function is similar to [`sync_all`], except that it might not
418     /// synchronize file metadata to the filesystem.
419     ///
420     /// This is intended for use cases that must synchronize content, but don't
421     /// need the metadata on disk. The goal of this method is to reduce disk
422     /// operations.
423     ///
424     /// Note that some platforms may simply implement this in terms of
425     /// [`sync_all`].
426     ///
427     /// [`sync_all`]: File::sync_all
428     ///
429     /// # Examples
430     ///
431     /// ```no_run
432     /// use std::fs::File;
433     /// use std::io::prelude::*;
434     ///
435     /// fn main() -> std::io::Result<()> {
436     ///     let mut f = File::create("foo.txt")?;
437     ///     f.write_all(b"Hello, world!")?;
438     ///
439     ///     f.sync_data()?;
440     ///     Ok(())
441     /// }
442     /// ```
443     #[stable(feature = "rust1", since = "1.0.0")]
444     pub fn sync_data(&self) -> io::Result<()> {
445         self.inner.datasync()
446     }
447
448     /// Truncates or extends the underlying file, updating the size of
449     /// this file to become `size`.
450     ///
451     /// If the `size` is less than the current file's size, then the file will
452     /// be shrunk. If it is greater than the current file's size, then the file
453     /// will be extended to `size` and have all of the intermediate data filled
454     /// in with 0s.
455     ///
456     /// The file's cursor isn't changed. In particular, if the cursor was at the
457     /// end and the file is shrunk using this operation, the cursor will now be
458     /// past the end.
459     ///
460     /// # Errors
461     ///
462     /// This function will return an error if the file is not opened for writing.
463     /// Also, std::io::ErrorKind::InvalidInput will be returned if the desired
464     /// length would cause an overflow due to the implementation specifics.
465     ///
466     /// # Examples
467     ///
468     /// ```no_run
469     /// use std::fs::File;
470     ///
471     /// fn main() -> std::io::Result<()> {
472     ///     let mut f = File::create("foo.txt")?;
473     ///     f.set_len(10)?;
474     ///     Ok(())
475     /// }
476     /// ```
477     ///
478     /// Note that this method alters the content of the underlying file, even
479     /// though it takes `&self` rather than `&mut self`.
480     #[stable(feature = "rust1", since = "1.0.0")]
481     pub fn set_len(&self, size: u64) -> io::Result<()> {
482         self.inner.truncate(size)
483     }
484
485     /// Queries metadata about the underlying file.
486     ///
487     /// # Examples
488     ///
489     /// ```no_run
490     /// use std::fs::File;
491     ///
492     /// fn main() -> std::io::Result<()> {
493     ///     let mut f = File::open("foo.txt")?;
494     ///     let metadata = f.metadata()?;
495     ///     Ok(())
496     /// }
497     /// ```
498     #[stable(feature = "rust1", since = "1.0.0")]
499     pub fn metadata(&self) -> io::Result<Metadata> {
500         self.inner.file_attr().map(Metadata)
501     }
502
503     /// Creates a new `File` instance that shares the same underlying file handle
504     /// as the existing `File` instance. Reads, writes, and seeks will affect
505     /// both `File` instances simultaneously.
506     ///
507     /// # Examples
508     ///
509     /// Creates two handles for a file named `foo.txt`:
510     ///
511     /// ```no_run
512     /// use std::fs::File;
513     ///
514     /// fn main() -> std::io::Result<()> {
515     ///     let mut file = File::open("foo.txt")?;
516     ///     let file_copy = file.try_clone()?;
517     ///     Ok(())
518     /// }
519     /// ```
520     ///
521     /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
522     /// two handles, seek one of them, and read the remaining bytes from the
523     /// other handle:
524     ///
525     /// ```no_run
526     /// use std::fs::File;
527     /// use std::io::SeekFrom;
528     /// use std::io::prelude::*;
529     ///
530     /// fn main() -> std::io::Result<()> {
531     ///     let mut file = File::open("foo.txt")?;
532     ///     let mut file_copy = file.try_clone()?;
533     ///
534     ///     file.seek(SeekFrom::Start(3))?;
535     ///
536     ///     let mut contents = vec![];
537     ///     file_copy.read_to_end(&mut contents)?;
538     ///     assert_eq!(contents, b"def\n");
539     ///     Ok(())
540     /// }
541     /// ```
542     #[stable(feature = "file_try_clone", since = "1.9.0")]
543     pub fn try_clone(&self) -> io::Result<File> {
544         Ok(File { inner: self.inner.duplicate()? })
545     }
546
547     /// Changes the permissions on the underlying file.
548     ///
549     /// # Platform-specific behavior
550     ///
551     /// This function currently corresponds to the `fchmod` function on Unix and
552     /// the `SetFileInformationByHandle` function on Windows. Note that, this
553     /// [may change in the future][changes].
554     ///
555     /// [changes]: io#platform-specific-behavior
556     ///
557     /// # Errors
558     ///
559     /// This function will return an error if the user lacks permission change
560     /// attributes on the underlying file. It may also return an error in other
561     /// os-specific unspecified cases.
562     ///
563     /// # Examples
564     ///
565     /// ```no_run
566     /// fn main() -> std::io::Result<()> {
567     ///     use std::fs::File;
568     ///
569     ///     let file = File::open("foo.txt")?;
570     ///     let mut perms = file.metadata()?.permissions();
571     ///     perms.set_readonly(true);
572     ///     file.set_permissions(perms)?;
573     ///     Ok(())
574     /// }
575     /// ```
576     ///
577     /// Note that this method alters the permissions of the underlying file,
578     /// even though it takes `&self` rather than `&mut self`.
579     #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
580     pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
581         self.inner.set_permissions(perm.0)
582     }
583 }
584
585 // In addition to the `impl`s here, `File` also has `impl`s for
586 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
587 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
588 // `AsHandle`/`From<OwnedHandle>`/`Into<OwnedHandle>` and
589 // `AsRawHandle`/`IntoRawHandle`/`FromRawHandle` on Windows.
590
591 impl AsInner<fs_imp::File> for File {
592     fn as_inner(&self) -> &fs_imp::File {
593         &self.inner
594     }
595 }
596 impl FromInner<fs_imp::File> for File {
597     fn from_inner(f: fs_imp::File) -> File {
598         File { inner: f }
599     }
600 }
601 impl IntoInner<fs_imp::File> for File {
602     fn into_inner(self) -> fs_imp::File {
603         self.inner
604     }
605 }
606
607 #[stable(feature = "rust1", since = "1.0.0")]
608 impl fmt::Debug for File {
609     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
610         self.inner.fmt(f)
611     }
612 }
613
614 /// Indicates how much extra capacity is needed to read the rest of the file.
615 fn buffer_capacity_required(mut file: &File) -> usize {
616     let size = file.metadata().map(|m| m.len()).unwrap_or(0);
617     let pos = file.stream_position().unwrap_or(0);
618     // Don't worry about `usize` overflow because reading will fail regardless
619     // in that case.
620     size.saturating_sub(pos) as usize
621 }
622
623 #[stable(feature = "rust1", since = "1.0.0")]
624 impl Read for File {
625     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
626         self.inner.read(buf)
627     }
628
629     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
630         self.inner.read_vectored(bufs)
631     }
632
633     fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
634         self.inner.read_buf(buf)
635     }
636
637     #[inline]
638     fn is_read_vectored(&self) -> bool {
639         self.inner.is_read_vectored()
640     }
641
642     // Reserves space in the buffer based on the file size when available.
643     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
644         buf.reserve(buffer_capacity_required(self));
645         io::default_read_to_end(self, buf)
646     }
647
648     // Reserves space in the buffer based on the file size when available.
649     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
650         buf.reserve(buffer_capacity_required(self));
651         io::default_read_to_string(self, buf)
652     }
653 }
654 #[stable(feature = "rust1", since = "1.0.0")]
655 impl Write for File {
656     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
657         self.inner.write(buf)
658     }
659
660     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
661         self.inner.write_vectored(bufs)
662     }
663
664     #[inline]
665     fn is_write_vectored(&self) -> bool {
666         self.inner.is_write_vectored()
667     }
668
669     fn flush(&mut self) -> io::Result<()> {
670         self.inner.flush()
671     }
672 }
673 #[stable(feature = "rust1", since = "1.0.0")]
674 impl Seek for File {
675     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
676         self.inner.seek(pos)
677     }
678 }
679 #[stable(feature = "rust1", since = "1.0.0")]
680 impl Read for &File {
681     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
682         self.inner.read(buf)
683     }
684
685     fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
686         self.inner.read_buf(buf)
687     }
688
689     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
690         self.inner.read_vectored(bufs)
691     }
692
693     #[inline]
694     fn is_read_vectored(&self) -> bool {
695         self.inner.is_read_vectored()
696     }
697
698     // Reserves space in the buffer based on the file size when available.
699     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
700         buf.reserve(buffer_capacity_required(self));
701         io::default_read_to_end(self, buf)
702     }
703
704     // Reserves space in the buffer based on the file size when available.
705     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
706         buf.reserve(buffer_capacity_required(self));
707         io::default_read_to_string(self, buf)
708     }
709 }
710 #[stable(feature = "rust1", since = "1.0.0")]
711 impl Write for &File {
712     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
713         self.inner.write(buf)
714     }
715
716     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
717         self.inner.write_vectored(bufs)
718     }
719
720     #[inline]
721     fn is_write_vectored(&self) -> bool {
722         self.inner.is_write_vectored()
723     }
724
725     fn flush(&mut self) -> io::Result<()> {
726         self.inner.flush()
727     }
728 }
729 #[stable(feature = "rust1", since = "1.0.0")]
730 impl Seek for &File {
731     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
732         self.inner.seek(pos)
733     }
734 }
735
736 impl OpenOptions {
737     /// Creates a blank new set of options ready for configuration.
738     ///
739     /// All options are initially set to `false`.
740     ///
741     /// # Examples
742     ///
743     /// ```no_run
744     /// use std::fs::OpenOptions;
745     ///
746     /// let mut options = OpenOptions::new();
747     /// let file = options.read(true).open("foo.txt");
748     /// ```
749     #[stable(feature = "rust1", since = "1.0.0")]
750     #[must_use]
751     pub fn new() -> Self {
752         OpenOptions(fs_imp::OpenOptions::new())
753     }
754
755     /// Sets the option for read access.
756     ///
757     /// This option, when true, will indicate that the file should be
758     /// `read`-able if opened.
759     ///
760     /// # Examples
761     ///
762     /// ```no_run
763     /// use std::fs::OpenOptions;
764     ///
765     /// let file = OpenOptions::new().read(true).open("foo.txt");
766     /// ```
767     #[stable(feature = "rust1", since = "1.0.0")]
768     pub fn read(&mut self, read: bool) -> &mut Self {
769         self.0.read(read);
770         self
771     }
772
773     /// Sets the option for write access.
774     ///
775     /// This option, when true, will indicate that the file should be
776     /// `write`-able if opened.
777     ///
778     /// If the file already exists, any write calls on it will overwrite its
779     /// contents, without truncating it.
780     ///
781     /// # Examples
782     ///
783     /// ```no_run
784     /// use std::fs::OpenOptions;
785     ///
786     /// let file = OpenOptions::new().write(true).open("foo.txt");
787     /// ```
788     #[stable(feature = "rust1", since = "1.0.0")]
789     pub fn write(&mut self, write: bool) -> &mut Self {
790         self.0.write(write);
791         self
792     }
793
794     /// Sets the option for the append mode.
795     ///
796     /// This option, when true, means that writes will append to a file instead
797     /// of overwriting previous contents.
798     /// Note that setting `.write(true).append(true)` has the same effect as
799     /// setting only `.append(true)`.
800     ///
801     /// For most filesystems, the operating system guarantees that all writes are
802     /// atomic: no writes get mangled because another process writes at the same
803     /// time.
804     ///
805     /// One maybe obvious note when using append-mode: make sure that all data
806     /// that belongs together is written to the file in one operation. This
807     /// can be done by concatenating strings before passing them to [`write()`],
808     /// or using a buffered writer (with a buffer of adequate size),
809     /// and calling [`flush()`] when the message is complete.
810     ///
811     /// If a file is opened with both read and append access, beware that after
812     /// opening, and after every write, the position for reading may be set at the
813     /// end of the file. So, before writing, save the current position (using
814     /// <code>[seek]\([SeekFrom]::[Current]\(0))</code>), and restore it before the next read.
815     ///
816     /// ## Note
817     ///
818     /// This function doesn't create the file if it doesn't exist. Use the
819     /// [`OpenOptions::create`] method to do so.
820     ///
821     /// [`write()`]: Write::write "io::Write::write"
822     /// [`flush()`]: Write::flush "io::Write::flush"
823     /// [seek]: Seek::seek "io::Seek::seek"
824     /// [Current]: SeekFrom::Current "io::SeekFrom::Current"
825     ///
826     /// # Examples
827     ///
828     /// ```no_run
829     /// use std::fs::OpenOptions;
830     ///
831     /// let file = OpenOptions::new().append(true).open("foo.txt");
832     /// ```
833     #[stable(feature = "rust1", since = "1.0.0")]
834     pub fn append(&mut self, append: bool) -> &mut Self {
835         self.0.append(append);
836         self
837     }
838
839     /// Sets the option for truncating a previous file.
840     ///
841     /// If a file is successfully opened with this option set it will truncate
842     /// the file to 0 length if it already exists.
843     ///
844     /// The file must be opened with write access for truncate to work.
845     ///
846     /// # Examples
847     ///
848     /// ```no_run
849     /// use std::fs::OpenOptions;
850     ///
851     /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
852     /// ```
853     #[stable(feature = "rust1", since = "1.0.0")]
854     pub fn truncate(&mut self, truncate: bool) -> &mut Self {
855         self.0.truncate(truncate);
856         self
857     }
858
859     /// Sets the option to create a new file, or open it if it already exists.
860     ///
861     /// In order for the file to be created, [`OpenOptions::write`] or
862     /// [`OpenOptions::append`] access must be used.
863     ///
864     /// # Examples
865     ///
866     /// ```no_run
867     /// use std::fs::OpenOptions;
868     ///
869     /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
870     /// ```
871     #[stable(feature = "rust1", since = "1.0.0")]
872     pub fn create(&mut self, create: bool) -> &mut Self {
873         self.0.create(create);
874         self
875     }
876
877     /// Sets the option to create a new file, failing if it already exists.
878     ///
879     /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
880     /// way, if the call succeeds, the file returned is guaranteed to be new.
881     ///
882     /// This option is useful because it is atomic. Otherwise between checking
883     /// whether a file exists and creating a new one, the file may have been
884     /// created by another process (a TOCTOU race condition / attack).
885     ///
886     /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
887     /// ignored.
888     ///
889     /// The file must be opened with write or append access in order to create
890     /// a new file.
891     ///
892     /// [`.create()`]: OpenOptions::create
893     /// [`.truncate()`]: OpenOptions::truncate
894     ///
895     /// # Examples
896     ///
897     /// ```no_run
898     /// use std::fs::OpenOptions;
899     ///
900     /// let file = OpenOptions::new().write(true)
901     ///                              .create_new(true)
902     ///                              .open("foo.txt");
903     /// ```
904     #[stable(feature = "expand_open_options2", since = "1.9.0")]
905     pub fn create_new(&mut self, create_new: bool) -> &mut Self {
906         self.0.create_new(create_new);
907         self
908     }
909
910     /// Opens a file at `path` with the options specified by `self`.
911     ///
912     /// # Errors
913     ///
914     /// This function will return an error under a number of different
915     /// circumstances. Some of these error conditions are listed here, together
916     /// with their [`io::ErrorKind`]. The mapping to [`io::ErrorKind`]s is not
917     /// part of the compatibility contract of the function.
918     ///
919     /// * [`NotFound`]: The specified file does not exist and neither `create`
920     ///   or `create_new` is set.
921     /// * [`NotFound`]: One of the directory components of the file path does
922     ///   not exist.
923     /// * [`PermissionDenied`]: The user lacks permission to get the specified
924     ///   access rights for the file.
925     /// * [`PermissionDenied`]: The user lacks permission to open one of the
926     ///   directory components of the specified path.
927     /// * [`AlreadyExists`]: `create_new` was specified and the file already
928     ///   exists.
929     /// * [`InvalidInput`]: Invalid combinations of open options (truncate
930     ///   without write access, no access mode set, etc.).
931     ///
932     /// The following errors don't match any existing [`io::ErrorKind`] at the moment:
933     /// * One of the directory components of the specified file path
934     ///   was not, in fact, a directory.
935     /// * Filesystem-level errors: full disk, write permission
936     ///   requested on a read-only file system, exceeded disk quota, too many
937     ///   open files, too long filename, too many symbolic links in the
938     ///   specified path (Unix-like systems only), etc.
939     ///
940     /// # Examples
941     ///
942     /// ```no_run
943     /// use std::fs::OpenOptions;
944     ///
945     /// let file = OpenOptions::new().read(true).open("foo.txt");
946     /// ```
947     ///
948     /// [`AlreadyExists`]: io::ErrorKind::AlreadyExists
949     /// [`InvalidInput`]: io::ErrorKind::InvalidInput
950     /// [`NotFound`]: io::ErrorKind::NotFound
951     /// [`PermissionDenied`]: io::ErrorKind::PermissionDenied
952     #[stable(feature = "rust1", since = "1.0.0")]
953     pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
954         self._open(path.as_ref())
955     }
956
957     fn _open(&self, path: &Path) -> io::Result<File> {
958         fs_imp::File::open(path, &self.0).map(|inner| File { inner })
959     }
960 }
961
962 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
963     fn as_inner(&self) -> &fs_imp::OpenOptions {
964         &self.0
965     }
966 }
967
968 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
969     fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
970         &mut self.0
971     }
972 }
973
974 impl Metadata {
975     /// Returns the file type for this metadata.
976     ///
977     /// # Examples
978     ///
979     /// ```no_run
980     /// fn main() -> std::io::Result<()> {
981     ///     use std::fs;
982     ///
983     ///     let metadata = fs::metadata("foo.txt")?;
984     ///
985     ///     println!("{:?}", metadata.file_type());
986     ///     Ok(())
987     /// }
988     /// ```
989     #[must_use]
990     #[stable(feature = "file_type", since = "1.1.0")]
991     pub fn file_type(&self) -> FileType {
992         FileType(self.0.file_type())
993     }
994
995     /// Returns `true` if this metadata is for a directory. The
996     /// result is mutually exclusive to the result of
997     /// [`Metadata::is_file`], and will be false for symlink metadata
998     /// obtained from [`symlink_metadata`].
999     ///
1000     /// # Examples
1001     ///
1002     /// ```no_run
1003     /// fn main() -> std::io::Result<()> {
1004     ///     use std::fs;
1005     ///
1006     ///     let metadata = fs::metadata("foo.txt")?;
1007     ///
1008     ///     assert!(!metadata.is_dir());
1009     ///     Ok(())
1010     /// }
1011     /// ```
1012     #[must_use]
1013     #[stable(feature = "rust1", since = "1.0.0")]
1014     pub fn is_dir(&self) -> bool {
1015         self.file_type().is_dir()
1016     }
1017
1018     /// Returns `true` if this metadata is for a regular file. The
1019     /// result is mutually exclusive to the result of
1020     /// [`Metadata::is_dir`], and will be false for symlink metadata
1021     /// obtained from [`symlink_metadata`].
1022     ///
1023     /// When the goal is simply to read from (or write to) the source, the most
1024     /// reliable way to test the source can be read (or written to) is to open
1025     /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1026     /// a Unix-like system for example. See [`File::open`] or
1027     /// [`OpenOptions::open`] for more information.
1028     ///
1029     /// # Examples
1030     ///
1031     /// ```no_run
1032     /// use std::fs;
1033     ///
1034     /// fn main() -> std::io::Result<()> {
1035     ///     let metadata = fs::metadata("foo.txt")?;
1036     ///
1037     ///     assert!(metadata.is_file());
1038     ///     Ok(())
1039     /// }
1040     /// ```
1041     #[must_use]
1042     #[stable(feature = "rust1", since = "1.0.0")]
1043     pub fn is_file(&self) -> bool {
1044         self.file_type().is_file()
1045     }
1046
1047     /// Returns `true` if this metadata is for a symbolic link.
1048     ///
1049     /// # Examples
1050     ///
1051     #[cfg_attr(unix, doc = "```no_run")]
1052     #[cfg_attr(not(unix), doc = "```ignore")]
1053     /// use std::fs;
1054     /// use std::path::Path;
1055     /// use std::os::unix::fs::symlink;
1056     ///
1057     /// fn main() -> std::io::Result<()> {
1058     ///     let link_path = Path::new("link");
1059     ///     symlink("/origin_does_not_exist/", link_path)?;
1060     ///
1061     ///     let metadata = fs::symlink_metadata(link_path)?;
1062     ///
1063     ///     assert!(metadata.is_symlink());
1064     ///     Ok(())
1065     /// }
1066     /// ```
1067     #[must_use]
1068     #[stable(feature = "is_symlink", since = "1.58.0")]
1069     pub fn is_symlink(&self) -> bool {
1070         self.file_type().is_symlink()
1071     }
1072
1073     /// Returns the size of the file, in bytes, this metadata is for.
1074     ///
1075     /// # Examples
1076     ///
1077     /// ```no_run
1078     /// use std::fs;
1079     ///
1080     /// fn main() -> std::io::Result<()> {
1081     ///     let metadata = fs::metadata("foo.txt")?;
1082     ///
1083     ///     assert_eq!(0, metadata.len());
1084     ///     Ok(())
1085     /// }
1086     /// ```
1087     #[must_use]
1088     #[stable(feature = "rust1", since = "1.0.0")]
1089     pub fn len(&self) -> u64 {
1090         self.0.size()
1091     }
1092
1093     /// Returns the permissions of the file this metadata is for.
1094     ///
1095     /// # Examples
1096     ///
1097     /// ```no_run
1098     /// use std::fs;
1099     ///
1100     /// fn main() -> std::io::Result<()> {
1101     ///     let metadata = fs::metadata("foo.txt")?;
1102     ///
1103     ///     assert!(!metadata.permissions().readonly());
1104     ///     Ok(())
1105     /// }
1106     /// ```
1107     #[must_use]
1108     #[stable(feature = "rust1", since = "1.0.0")]
1109     pub fn permissions(&self) -> Permissions {
1110         Permissions(self.0.perm())
1111     }
1112
1113     /// Returns the last modification time listed in this metadata.
1114     ///
1115     /// The returned value corresponds to the `mtime` field of `stat` on Unix
1116     /// platforms and the `ftLastWriteTime` field on Windows platforms.
1117     ///
1118     /// # Errors
1119     ///
1120     /// This field might not be available on all platforms, and will return an
1121     /// `Err` on platforms where it is not available.
1122     ///
1123     /// # Examples
1124     ///
1125     /// ```no_run
1126     /// use std::fs;
1127     ///
1128     /// fn main() -> std::io::Result<()> {
1129     ///     let metadata = fs::metadata("foo.txt")?;
1130     ///
1131     ///     if let Ok(time) = metadata.modified() {
1132     ///         println!("{time:?}");
1133     ///     } else {
1134     ///         println!("Not supported on this platform");
1135     ///     }
1136     ///     Ok(())
1137     /// }
1138     /// ```
1139     #[stable(feature = "fs_time", since = "1.10.0")]
1140     pub fn modified(&self) -> io::Result<SystemTime> {
1141         self.0.modified().map(FromInner::from_inner)
1142     }
1143
1144     /// Returns the last access time of this metadata.
1145     ///
1146     /// The returned value corresponds to the `atime` field of `stat` on Unix
1147     /// platforms and the `ftLastAccessTime` field on Windows platforms.
1148     ///
1149     /// Note that not all platforms will keep this field update in a file's
1150     /// metadata, for example Windows has an option to disable updating this
1151     /// time when files are accessed and Linux similarly has `noatime`.
1152     ///
1153     /// # Errors
1154     ///
1155     /// This field might not be available on all platforms, and will return an
1156     /// `Err` on platforms where it is not available.
1157     ///
1158     /// # Examples
1159     ///
1160     /// ```no_run
1161     /// use std::fs;
1162     ///
1163     /// fn main() -> std::io::Result<()> {
1164     ///     let metadata = fs::metadata("foo.txt")?;
1165     ///
1166     ///     if let Ok(time) = metadata.accessed() {
1167     ///         println!("{time:?}");
1168     ///     } else {
1169     ///         println!("Not supported on this platform");
1170     ///     }
1171     ///     Ok(())
1172     /// }
1173     /// ```
1174     #[stable(feature = "fs_time", since = "1.10.0")]
1175     pub fn accessed(&self) -> io::Result<SystemTime> {
1176         self.0.accessed().map(FromInner::from_inner)
1177     }
1178
1179     /// Returns the creation time listed in this metadata.
1180     ///
1181     /// The returned value corresponds to the `btime` field of `statx` on
1182     /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1183     /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1184     ///
1185     /// # Errors
1186     ///
1187     /// This field might not be available on all platforms, and will return an
1188     /// `Err` on platforms or filesystems where it is not available.
1189     ///
1190     /// # Examples
1191     ///
1192     /// ```no_run
1193     /// use std::fs;
1194     ///
1195     /// fn main() -> std::io::Result<()> {
1196     ///     let metadata = fs::metadata("foo.txt")?;
1197     ///
1198     ///     if let Ok(time) = metadata.created() {
1199     ///         println!("{time:?}");
1200     ///     } else {
1201     ///         println!("Not supported on this platform or filesystem");
1202     ///     }
1203     ///     Ok(())
1204     /// }
1205     /// ```
1206     #[stable(feature = "fs_time", since = "1.10.0")]
1207     pub fn created(&self) -> io::Result<SystemTime> {
1208         self.0.created().map(FromInner::from_inner)
1209     }
1210 }
1211
1212 #[stable(feature = "std_debug", since = "1.16.0")]
1213 impl fmt::Debug for Metadata {
1214     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1215         f.debug_struct("Metadata")
1216             .field("file_type", &self.file_type())
1217             .field("is_dir", &self.is_dir())
1218             .field("is_file", &self.is_file())
1219             .field("permissions", &self.permissions())
1220             .field("modified", &self.modified())
1221             .field("accessed", &self.accessed())
1222             .field("created", &self.created())
1223             .finish_non_exhaustive()
1224     }
1225 }
1226
1227 impl AsInner<fs_imp::FileAttr> for Metadata {
1228     fn as_inner(&self) -> &fs_imp::FileAttr {
1229         &self.0
1230     }
1231 }
1232
1233 impl FromInner<fs_imp::FileAttr> for Metadata {
1234     fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1235         Metadata(attr)
1236     }
1237 }
1238
1239 impl Permissions {
1240     /// Returns `true` if these permissions describe a readonly (unwritable) file.
1241     ///
1242     /// # Examples
1243     ///
1244     /// ```no_run
1245     /// use std::fs::File;
1246     ///
1247     /// fn main() -> std::io::Result<()> {
1248     ///     let mut f = File::create("foo.txt")?;
1249     ///     let metadata = f.metadata()?;
1250     ///
1251     ///     assert_eq!(false, metadata.permissions().readonly());
1252     ///     Ok(())
1253     /// }
1254     /// ```
1255     #[must_use = "call `set_readonly` to modify the readonly flag"]
1256     #[stable(feature = "rust1", since = "1.0.0")]
1257     pub fn readonly(&self) -> bool {
1258         self.0.readonly()
1259     }
1260
1261     /// Modifies the readonly flag for this set of permissions. If the
1262     /// `readonly` argument is `true`, using the resulting `Permission` will
1263     /// update file permissions to forbid writing. Conversely, if it's `false`,
1264     /// using the resulting `Permission` will update file permissions to allow
1265     /// writing.
1266     ///
1267     /// This operation does **not** modify the filesystem. To modify the
1268     /// filesystem use the [`set_permissions`] function.
1269     ///
1270     /// # Examples
1271     ///
1272     /// ```no_run
1273     /// use std::fs::File;
1274     ///
1275     /// fn main() -> std::io::Result<()> {
1276     ///     let f = File::create("foo.txt")?;
1277     ///     let metadata = f.metadata()?;
1278     ///     let mut permissions = metadata.permissions();
1279     ///
1280     ///     permissions.set_readonly(true);
1281     ///
1282     ///     // filesystem doesn't change
1283     ///     assert_eq!(false, metadata.permissions().readonly());
1284     ///
1285     ///     // just this particular `permissions`.
1286     ///     assert_eq!(true, permissions.readonly());
1287     ///     Ok(())
1288     /// }
1289     /// ```
1290     #[stable(feature = "rust1", since = "1.0.0")]
1291     pub fn set_readonly(&mut self, readonly: bool) {
1292         self.0.set_readonly(readonly)
1293     }
1294 }
1295
1296 impl FileType {
1297     /// Tests whether this file type represents a directory. The
1298     /// result is mutually exclusive to the results of
1299     /// [`is_file`] and [`is_symlink`]; only zero or one of these
1300     /// tests may pass.
1301     ///
1302     /// [`is_file`]: FileType::is_file
1303     /// [`is_symlink`]: FileType::is_symlink
1304     ///
1305     /// # Examples
1306     ///
1307     /// ```no_run
1308     /// fn main() -> std::io::Result<()> {
1309     ///     use std::fs;
1310     ///
1311     ///     let metadata = fs::metadata("foo.txt")?;
1312     ///     let file_type = metadata.file_type();
1313     ///
1314     ///     assert_eq!(file_type.is_dir(), false);
1315     ///     Ok(())
1316     /// }
1317     /// ```
1318     #[must_use]
1319     #[stable(feature = "file_type", since = "1.1.0")]
1320     pub fn is_dir(&self) -> bool {
1321         self.0.is_dir()
1322     }
1323
1324     /// Tests whether this file type represents a regular file.
1325     /// The result is  mutually exclusive to the results of
1326     /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1327     /// tests may pass.
1328     ///
1329     /// When the goal is simply to read from (or write to) the source, the most
1330     /// reliable way to test the source can be read (or written to) is to open
1331     /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1332     /// a Unix-like system for example. See [`File::open`] or
1333     /// [`OpenOptions::open`] for more information.
1334     ///
1335     /// [`is_dir`]: FileType::is_dir
1336     /// [`is_symlink`]: FileType::is_symlink
1337     ///
1338     /// # Examples
1339     ///
1340     /// ```no_run
1341     /// fn main() -> std::io::Result<()> {
1342     ///     use std::fs;
1343     ///
1344     ///     let metadata = fs::metadata("foo.txt")?;
1345     ///     let file_type = metadata.file_type();
1346     ///
1347     ///     assert_eq!(file_type.is_file(), true);
1348     ///     Ok(())
1349     /// }
1350     /// ```
1351     #[must_use]
1352     #[stable(feature = "file_type", since = "1.1.0")]
1353     pub fn is_file(&self) -> bool {
1354         self.0.is_file()
1355     }
1356
1357     /// Tests whether this file type represents a symbolic link.
1358     /// The result is mutually exclusive to the results of
1359     /// [`is_dir`] and [`is_file`]; only zero or one of these
1360     /// tests may pass.
1361     ///
1362     /// The underlying [`Metadata`] struct needs to be retrieved
1363     /// with the [`fs::symlink_metadata`] function and not the
1364     /// [`fs::metadata`] function. The [`fs::metadata`] function
1365     /// follows symbolic links, so [`is_symlink`] would always
1366     /// return `false` for the target file.
1367     ///
1368     /// [`fs::metadata`]: metadata
1369     /// [`fs::symlink_metadata`]: symlink_metadata
1370     /// [`is_dir`]: FileType::is_dir
1371     /// [`is_file`]: FileType::is_file
1372     /// [`is_symlink`]: FileType::is_symlink
1373     ///
1374     /// # Examples
1375     ///
1376     /// ```no_run
1377     /// use std::fs;
1378     ///
1379     /// fn main() -> std::io::Result<()> {
1380     ///     let metadata = fs::symlink_metadata("foo.txt")?;
1381     ///     let file_type = metadata.file_type();
1382     ///
1383     ///     assert_eq!(file_type.is_symlink(), false);
1384     ///     Ok(())
1385     /// }
1386     /// ```
1387     #[must_use]
1388     #[stable(feature = "file_type", since = "1.1.0")]
1389     pub fn is_symlink(&self) -> bool {
1390         self.0.is_symlink()
1391     }
1392 }
1393
1394 impl AsInner<fs_imp::FileType> for FileType {
1395     fn as_inner(&self) -> &fs_imp::FileType {
1396         &self.0
1397     }
1398 }
1399
1400 impl FromInner<fs_imp::FilePermissions> for Permissions {
1401     fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1402         Permissions(f)
1403     }
1404 }
1405
1406 impl AsInner<fs_imp::FilePermissions> for Permissions {
1407     fn as_inner(&self) -> &fs_imp::FilePermissions {
1408         &self.0
1409     }
1410 }
1411
1412 #[stable(feature = "rust1", since = "1.0.0")]
1413 impl Iterator for ReadDir {
1414     type Item = io::Result<DirEntry>;
1415
1416     fn next(&mut self) -> Option<io::Result<DirEntry>> {
1417         self.0.next().map(|entry| entry.map(DirEntry))
1418     }
1419 }
1420
1421 impl DirEntry {
1422     /// Returns the full path to the file that this entry represents.
1423     ///
1424     /// The full path is created by joining the original path to `read_dir`
1425     /// with the filename of this entry.
1426     ///
1427     /// # Examples
1428     ///
1429     /// ```no_run
1430     /// use std::fs;
1431     ///
1432     /// fn main() -> std::io::Result<()> {
1433     ///     for entry in fs::read_dir(".")? {
1434     ///         let dir = entry?;
1435     ///         println!("{:?}", dir.path());
1436     ///     }
1437     ///     Ok(())
1438     /// }
1439     /// ```
1440     ///
1441     /// This prints output like:
1442     ///
1443     /// ```text
1444     /// "./whatever.txt"
1445     /// "./foo.html"
1446     /// "./hello_world.rs"
1447     /// ```
1448     ///
1449     /// The exact text, of course, depends on what files you have in `.`.
1450     #[must_use]
1451     #[stable(feature = "rust1", since = "1.0.0")]
1452     pub fn path(&self) -> PathBuf {
1453         self.0.path()
1454     }
1455
1456     /// Returns the metadata for the file that this entry points at.
1457     ///
1458     /// This function will not traverse symlinks if this entry points at a
1459     /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1460     ///
1461     /// [`fs::metadata`]: metadata
1462     /// [`fs::File::metadata`]: File::metadata
1463     ///
1464     /// # Platform-specific behavior
1465     ///
1466     /// On Windows this function is cheap to call (no extra system calls
1467     /// needed), but on Unix platforms this function is the equivalent of
1468     /// calling `symlink_metadata` on the path.
1469     ///
1470     /// # Examples
1471     ///
1472     /// ```
1473     /// use std::fs;
1474     ///
1475     /// if let Ok(entries) = fs::read_dir(".") {
1476     ///     for entry in entries {
1477     ///         if let Ok(entry) = entry {
1478     ///             // Here, `entry` is a `DirEntry`.
1479     ///             if let Ok(metadata) = entry.metadata() {
1480     ///                 // Now let's show our entry's permissions!
1481     ///                 println!("{:?}: {:?}", entry.path(), metadata.permissions());
1482     ///             } else {
1483     ///                 println!("Couldn't get metadata for {:?}", entry.path());
1484     ///             }
1485     ///         }
1486     ///     }
1487     /// }
1488     /// ```
1489     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1490     pub fn metadata(&self) -> io::Result<Metadata> {
1491         self.0.metadata().map(Metadata)
1492     }
1493
1494     /// Returns the file type for the file that this entry points at.
1495     ///
1496     /// This function will not traverse symlinks if this entry points at a
1497     /// symlink.
1498     ///
1499     /// # Platform-specific behavior
1500     ///
1501     /// On Windows and most Unix platforms this function is free (no extra
1502     /// system calls needed), but some Unix platforms may require the equivalent
1503     /// call to `symlink_metadata` to learn about the target file type.
1504     ///
1505     /// # Examples
1506     ///
1507     /// ```
1508     /// use std::fs;
1509     ///
1510     /// if let Ok(entries) = fs::read_dir(".") {
1511     ///     for entry in entries {
1512     ///         if let Ok(entry) = entry {
1513     ///             // Here, `entry` is a `DirEntry`.
1514     ///             if let Ok(file_type) = entry.file_type() {
1515     ///                 // Now let's show our entry's file type!
1516     ///                 println!("{:?}: {:?}", entry.path(), file_type);
1517     ///             } else {
1518     ///                 println!("Couldn't get file type for {:?}", entry.path());
1519     ///             }
1520     ///         }
1521     ///     }
1522     /// }
1523     /// ```
1524     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1525     pub fn file_type(&self) -> io::Result<FileType> {
1526         self.0.file_type().map(FileType)
1527     }
1528
1529     /// Returns the bare file name of this directory entry without any other
1530     /// leading path component.
1531     ///
1532     /// # Examples
1533     ///
1534     /// ```
1535     /// use std::fs;
1536     ///
1537     /// if let Ok(entries) = fs::read_dir(".") {
1538     ///     for entry in entries {
1539     ///         if let Ok(entry) = entry {
1540     ///             // Here, `entry` is a `DirEntry`.
1541     ///             println!("{:?}", entry.file_name());
1542     ///         }
1543     ///     }
1544     /// }
1545     /// ```
1546     #[must_use]
1547     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1548     pub fn file_name(&self) -> OsString {
1549         self.0.file_name()
1550     }
1551 }
1552
1553 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1554 impl fmt::Debug for DirEntry {
1555     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1556         f.debug_tuple("DirEntry").field(&self.path()).finish()
1557     }
1558 }
1559
1560 impl AsInner<fs_imp::DirEntry> for DirEntry {
1561     fn as_inner(&self) -> &fs_imp::DirEntry {
1562         &self.0
1563     }
1564 }
1565
1566 /// Removes a file from the filesystem.
1567 ///
1568 /// Note that there is no
1569 /// guarantee that the file is immediately deleted (e.g., depending on
1570 /// platform, other open file descriptors may prevent immediate removal).
1571 ///
1572 /// # Platform-specific behavior
1573 ///
1574 /// This function currently corresponds to the `unlink` function on Unix
1575 /// and the `DeleteFile` function on Windows.
1576 /// Note that, this [may change in the future][changes].
1577 ///
1578 /// [changes]: io#platform-specific-behavior
1579 ///
1580 /// # Errors
1581 ///
1582 /// This function will return an error in the following situations, but is not
1583 /// limited to just these cases:
1584 ///
1585 /// * `path` points to a directory.
1586 /// * The file doesn't exist.
1587 /// * The user lacks permissions to remove the file.
1588 ///
1589 /// # Examples
1590 ///
1591 /// ```no_run
1592 /// use std::fs;
1593 ///
1594 /// fn main() -> std::io::Result<()> {
1595 ///     fs::remove_file("a.txt")?;
1596 ///     Ok(())
1597 /// }
1598 /// ```
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1601     fs_imp::unlink(path.as_ref())
1602 }
1603
1604 /// Given a path, query the file system to get information about a file,
1605 /// directory, etc.
1606 ///
1607 /// This function will traverse symbolic links to query information about the
1608 /// destination file.
1609 ///
1610 /// # Platform-specific behavior
1611 ///
1612 /// This function currently corresponds to the `stat` function on Unix
1613 /// and the `GetFileAttributesEx` function on Windows.
1614 /// Note that, this [may change in the future][changes].
1615 ///
1616 /// [changes]: io#platform-specific-behavior
1617 ///
1618 /// # Errors
1619 ///
1620 /// This function will return an error in the following situations, but is not
1621 /// limited to just these cases:
1622 ///
1623 /// * The user lacks permissions to perform `metadata` call on `path`.
1624 /// * `path` does not exist.
1625 ///
1626 /// # Examples
1627 ///
1628 /// ```rust,no_run
1629 /// use std::fs;
1630 ///
1631 /// fn main() -> std::io::Result<()> {
1632 ///     let attr = fs::metadata("/some/file/path.txt")?;
1633 ///     // inspect attr ...
1634 ///     Ok(())
1635 /// }
1636 /// ```
1637 #[stable(feature = "rust1", since = "1.0.0")]
1638 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1639     fs_imp::stat(path.as_ref()).map(Metadata)
1640 }
1641
1642 /// Query the metadata about a file without following symlinks.
1643 ///
1644 /// # Platform-specific behavior
1645 ///
1646 /// This function currently corresponds to the `lstat` function on Unix
1647 /// and the `GetFileAttributesEx` function on Windows.
1648 /// Note that, this [may change in the future][changes].
1649 ///
1650 /// [changes]: io#platform-specific-behavior
1651 ///
1652 /// # Errors
1653 ///
1654 /// This function will return an error in the following situations, but is not
1655 /// limited to just these cases:
1656 ///
1657 /// * The user lacks permissions to perform `metadata` call on `path`.
1658 /// * `path` does not exist.
1659 ///
1660 /// # Examples
1661 ///
1662 /// ```rust,no_run
1663 /// use std::fs;
1664 ///
1665 /// fn main() -> std::io::Result<()> {
1666 ///     let attr = fs::symlink_metadata("/some/file/path.txt")?;
1667 ///     // inspect attr ...
1668 ///     Ok(())
1669 /// }
1670 /// ```
1671 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1672 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1673     fs_imp::lstat(path.as_ref()).map(Metadata)
1674 }
1675
1676 /// Rename a file or directory to a new name, replacing the original file if
1677 /// `to` already exists.
1678 ///
1679 /// This will not work if the new name is on a different mount point.
1680 ///
1681 /// # Platform-specific behavior
1682 ///
1683 /// This function currently corresponds to the `rename` function on Unix
1684 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1685 ///
1686 /// Because of this, the behavior when both `from` and `to` exist differs. On
1687 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1688 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1689 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1690 ///
1691 /// Note that, this [may change in the future][changes].
1692 ///
1693 /// [changes]: io#platform-specific-behavior
1694 ///
1695 /// # Errors
1696 ///
1697 /// This function will return an error in the following situations, but is not
1698 /// limited to just these cases:
1699 ///
1700 /// * `from` does not exist.
1701 /// * The user lacks permissions to view contents.
1702 /// * `from` and `to` are on separate filesystems.
1703 ///
1704 /// # Examples
1705 ///
1706 /// ```no_run
1707 /// use std::fs;
1708 ///
1709 /// fn main() -> std::io::Result<()> {
1710 ///     fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1711 ///     Ok(())
1712 /// }
1713 /// ```
1714 #[stable(feature = "rust1", since = "1.0.0")]
1715 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1716     fs_imp::rename(from.as_ref(), to.as_ref())
1717 }
1718
1719 /// Copies the contents of one file to another. This function will also
1720 /// copy the permission bits of the original file to the destination file.
1721 ///
1722 /// This function will **overwrite** the contents of `to`.
1723 ///
1724 /// Note that if `from` and `to` both point to the same file, then the file
1725 /// will likely get truncated by this operation.
1726 ///
1727 /// On success, the total number of bytes copied is returned and it is equal to
1728 /// the length of the `to` file as reported by `metadata`.
1729 ///
1730 /// If you’re wanting to copy the contents of one file to another and you’re
1731 /// working with [`File`]s, see the [`io::copy()`] function.
1732 ///
1733 /// # Platform-specific behavior
1734 ///
1735 /// This function currently corresponds to the `open` function in Unix
1736 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1737 /// `O_CLOEXEC` is set for returned file descriptors.
1738 ///
1739 /// On Linux (including Android), this function attempts to use `copy_file_range(2)`,
1740 /// and falls back to reading and writing if that is not possible.
1741 ///
1742 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1743 /// NTFS streams are copied but only the size of the main stream is returned by
1744 /// this function.
1745 ///
1746 /// On MacOS, this function corresponds to `fclonefileat` and `fcopyfile`.
1747 ///
1748 /// Note that platform-specific behavior [may change in the future][changes].
1749 ///
1750 /// [changes]: io#platform-specific-behavior
1751 ///
1752 /// # Errors
1753 ///
1754 /// This function will return an error in the following situations, but is not
1755 /// limited to just these cases:
1756 ///
1757 /// * `from` is neither a regular file nor a symlink to a regular file.
1758 /// * `from` does not exist.
1759 /// * The current process does not have the permission rights to read
1760 ///   `from` or write `to`.
1761 ///
1762 /// # Examples
1763 ///
1764 /// ```no_run
1765 /// use std::fs;
1766 ///
1767 /// fn main() -> std::io::Result<()> {
1768 ///     fs::copy("foo.txt", "bar.txt")?;  // Copy foo.txt to bar.txt
1769 ///     Ok(())
1770 /// }
1771 /// ```
1772 #[stable(feature = "rust1", since = "1.0.0")]
1773 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1774     fs_imp::copy(from.as_ref(), to.as_ref())
1775 }
1776
1777 /// Creates a new hard link on the filesystem.
1778 ///
1779 /// The `link` path will be a link pointing to the `original` path. Note that
1780 /// systems often require these two paths to both be located on the same
1781 /// filesystem.
1782 ///
1783 /// If `original` names a symbolic link, it is platform-specific whether the
1784 /// symbolic link is followed. On platforms where it's possible to not follow
1785 /// it, it is not followed, and the created hard link points to the symbolic
1786 /// link itself.
1787 ///
1788 /// # Platform-specific behavior
1789 ///
1790 /// This function currently corresponds the `CreateHardLink` function on Windows.
1791 /// On most Unix systems, it corresponds to the `linkat` function with no flags.
1792 /// On Android, VxWorks, and Redox, it instead corresponds to the `link` function.
1793 /// On MacOS, it uses the `linkat` function if it is available, but on very old
1794 /// systems where `linkat` is not available, `link` is selected at runtime instead.
1795 /// Note that, this [may change in the future][changes].
1796 ///
1797 /// [changes]: io#platform-specific-behavior
1798 ///
1799 /// # Errors
1800 ///
1801 /// This function will return an error in the following situations, but is not
1802 /// limited to just these cases:
1803 ///
1804 /// * The `original` path is not a file or doesn't exist.
1805 ///
1806 /// # Examples
1807 ///
1808 /// ```no_run
1809 /// use std::fs;
1810 ///
1811 /// fn main() -> std::io::Result<()> {
1812 ///     fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1813 ///     Ok(())
1814 /// }
1815 /// ```
1816 #[stable(feature = "rust1", since = "1.0.0")]
1817 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1818     fs_imp::link(original.as_ref(), link.as_ref())
1819 }
1820
1821 /// Creates a new symbolic link on the filesystem.
1822 ///
1823 /// The `link` path will be a symbolic link pointing to the `original` path.
1824 /// On Windows, this will be a file symlink, not a directory symlink;
1825 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1826 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1827 /// used instead to make the intent explicit.
1828 ///
1829 /// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
1830 /// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
1831 /// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
1832 ///
1833 /// # Examples
1834 ///
1835 /// ```no_run
1836 /// use std::fs;
1837 ///
1838 /// fn main() -> std::io::Result<()> {
1839 ///     fs::soft_link("a.txt", "b.txt")?;
1840 ///     Ok(())
1841 /// }
1842 /// ```
1843 #[stable(feature = "rust1", since = "1.0.0")]
1844 #[rustc_deprecated(
1845     since = "1.1.0",
1846     reason = "replaced with std::os::unix::fs::symlink and \
1847               std::os::windows::fs::{symlink_file, symlink_dir}"
1848 )]
1849 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1850     fs_imp::symlink(original.as_ref(), link.as_ref())
1851 }
1852
1853 /// Reads a symbolic link, returning the file that the link points to.
1854 ///
1855 /// # Platform-specific behavior
1856 ///
1857 /// This function currently corresponds to the `readlink` function on Unix
1858 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1859 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1860 /// Note that, this [may change in the future][changes].
1861 ///
1862 /// [changes]: io#platform-specific-behavior
1863 ///
1864 /// # Errors
1865 ///
1866 /// This function will return an error in the following situations, but is not
1867 /// limited to just these cases:
1868 ///
1869 /// * `path` is not a symbolic link.
1870 /// * `path` does not exist.
1871 ///
1872 /// # Examples
1873 ///
1874 /// ```no_run
1875 /// use std::fs;
1876 ///
1877 /// fn main() -> std::io::Result<()> {
1878 ///     let path = fs::read_link("a.txt")?;
1879 ///     Ok(())
1880 /// }
1881 /// ```
1882 #[stable(feature = "rust1", since = "1.0.0")]
1883 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1884     fs_imp::readlink(path.as_ref())
1885 }
1886
1887 /// Returns the canonical, absolute form of a path with all intermediate
1888 /// components normalized and symbolic links resolved.
1889 ///
1890 /// # Platform-specific behavior
1891 ///
1892 /// This function currently corresponds to the `realpath` function on Unix
1893 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1894 /// Note that, this [may change in the future][changes].
1895 ///
1896 /// On Windows, this converts the path to use [extended length path][path]
1897 /// syntax, which allows your program to use longer path names, but means you
1898 /// can only join backslash-delimited paths to it, and it may be incompatible
1899 /// with other applications (if passed to the application on the command-line,
1900 /// or written to a file another application may read).
1901 ///
1902 /// [changes]: io#platform-specific-behavior
1903 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1904 ///
1905 /// # Errors
1906 ///
1907 /// This function will return an error in the following situations, but is not
1908 /// limited to just these cases:
1909 ///
1910 /// * `path` does not exist.
1911 /// * A non-final component in path is not a directory.
1912 ///
1913 /// # Examples
1914 ///
1915 /// ```no_run
1916 /// use std::fs;
1917 ///
1918 /// fn main() -> std::io::Result<()> {
1919 ///     let path = fs::canonicalize("../a/../foo.txt")?;
1920 ///     Ok(())
1921 /// }
1922 /// ```
1923 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1924 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1925     fs_imp::canonicalize(path.as_ref())
1926 }
1927
1928 /// Creates a new, empty directory at the provided path
1929 ///
1930 /// # Platform-specific behavior
1931 ///
1932 /// This function currently corresponds to the `mkdir` function on Unix
1933 /// and the `CreateDirectory` function on Windows.
1934 /// Note that, this [may change in the future][changes].
1935 ///
1936 /// [changes]: io#platform-specific-behavior
1937 ///
1938 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1939 /// return an error. To create a directory and all its missing parents at the
1940 /// same time, use the [`create_dir_all`] function.
1941 ///
1942 /// # Errors
1943 ///
1944 /// This function will return an error in the following situations, but is not
1945 /// limited to just these cases:
1946 ///
1947 /// * User lacks permissions to create directory at `path`.
1948 /// * A parent of the given path doesn't exist. (To create a directory and all
1949 ///   its missing parents at the same time, use the [`create_dir_all`]
1950 ///   function.)
1951 /// * `path` already exists.
1952 ///
1953 /// # Examples
1954 ///
1955 /// ```no_run
1956 /// use std::fs;
1957 ///
1958 /// fn main() -> std::io::Result<()> {
1959 ///     fs::create_dir("/some/dir")?;
1960 ///     Ok(())
1961 /// }
1962 /// ```
1963 #[doc(alias = "mkdir")]
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1966     DirBuilder::new().create(path.as_ref())
1967 }
1968
1969 /// Recursively create a directory and all of its parent components if they
1970 /// are missing.
1971 ///
1972 /// # Platform-specific behavior
1973 ///
1974 /// This function currently corresponds to the `mkdir` function on Unix
1975 /// and the `CreateDirectory` function on Windows.
1976 /// Note that, this [may change in the future][changes].
1977 ///
1978 /// [changes]: io#platform-specific-behavior
1979 ///
1980 /// # Errors
1981 ///
1982 /// This function will return an error in the following situations, but is not
1983 /// limited to just these cases:
1984 ///
1985 /// * If any directory in the path specified by `path`
1986 /// does not already exist and it could not be created otherwise. The specific
1987 /// error conditions for when a directory is being created (after it is
1988 /// determined to not exist) are outlined by [`fs::create_dir`].
1989 ///
1990 /// Notable exception is made for situations where any of the directories
1991 /// specified in the `path` could not be created as it was being created concurrently.
1992 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1993 /// concurrently from multiple threads or processes is guaranteed not to fail
1994 /// due to a race condition with itself.
1995 ///
1996 /// [`fs::create_dir`]: create_dir
1997 ///
1998 /// # Examples
1999 ///
2000 /// ```no_run
2001 /// use std::fs;
2002 ///
2003 /// fn main() -> std::io::Result<()> {
2004 ///     fs::create_dir_all("/some/dir")?;
2005 ///     Ok(())
2006 /// }
2007 /// ```
2008 #[stable(feature = "rust1", since = "1.0.0")]
2009 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2010     DirBuilder::new().recursive(true).create(path.as_ref())
2011 }
2012
2013 /// Removes an empty directory.
2014 ///
2015 /// # Platform-specific behavior
2016 ///
2017 /// This function currently corresponds to the `rmdir` function on Unix
2018 /// and the `RemoveDirectory` function on Windows.
2019 /// Note that, this [may change in the future][changes].
2020 ///
2021 /// [changes]: io#platform-specific-behavior
2022 ///
2023 /// # Errors
2024 ///
2025 /// This function will return an error in the following situations, but is not
2026 /// limited to just these cases:
2027 ///
2028 /// * `path` doesn't exist.
2029 /// * `path` isn't a directory.
2030 /// * The user lacks permissions to remove the directory at the provided `path`.
2031 /// * The directory isn't empty.
2032 ///
2033 /// # Examples
2034 ///
2035 /// ```no_run
2036 /// use std::fs;
2037 ///
2038 /// fn main() -> std::io::Result<()> {
2039 ///     fs::remove_dir("/some/dir")?;
2040 ///     Ok(())
2041 /// }
2042 /// ```
2043 #[doc(alias = "rmdir")]
2044 #[stable(feature = "rust1", since = "1.0.0")]
2045 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2046     fs_imp::rmdir(path.as_ref())
2047 }
2048
2049 /// Removes a directory at this path, after removing all its contents. Use
2050 /// carefully!
2051 ///
2052 /// This function does **not** follow symbolic links and it will simply remove the
2053 /// symbolic link itself.
2054 ///
2055 /// # Platform-specific behavior
2056 ///
2057 /// This function currently corresponds to `openat`, `fdopendir`, `unlinkat` and `lstat` functions
2058 /// on Unix (except for macOS before version 10.10 and REDOX) and the `CreateFileW`,
2059 /// `GetFileInformationByHandleEx`, `SetFileInformationByHandle`, and `NtCreateFile` functions on
2060 /// Windows. Note that, this [may change in the future][changes].
2061 ///
2062 /// [changes]: io#platform-specific-behavior
2063 ///
2064 /// On macOS before version 10.10 and REDOX, as well as when running in Miri for any target, this
2065 /// function is not protected against time-of-check to time-of-use (TOCTOU) race conditions, and
2066 /// should not be used in security-sensitive code on those platforms. All other platforms are
2067 /// protected.
2068 ///
2069 /// # Errors
2070 ///
2071 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2072 ///
2073 /// [`fs::remove_file`]: remove_file
2074 /// [`fs::remove_dir`]: remove_dir
2075 ///
2076 /// # Examples
2077 ///
2078 /// ```no_run
2079 /// use std::fs;
2080 ///
2081 /// fn main() -> std::io::Result<()> {
2082 ///     fs::remove_dir_all("/some/dir")?;
2083 ///     Ok(())
2084 /// }
2085 /// ```
2086 #[stable(feature = "rust1", since = "1.0.0")]
2087 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2088     fs_imp::remove_dir_all(path.as_ref())
2089 }
2090
2091 /// Returns an iterator over the entries within a directory.
2092 ///
2093 /// The iterator will yield instances of <code>[io::Result]<[DirEntry]></code>.
2094 /// New errors may be encountered after an iterator is initially constructed.
2095 /// Entries for the current and parent directories (typically `.` and `..`) are
2096 /// skipped.
2097 ///
2098 /// # Platform-specific behavior
2099 ///
2100 /// This function currently corresponds to the `opendir` function on Unix
2101 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2102 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2103 /// Note that, this [may change in the future][changes].
2104 ///
2105 /// [changes]: io#platform-specific-behavior
2106 ///
2107 /// The order in which this iterator returns entries is platform and filesystem
2108 /// dependent.
2109 ///
2110 /// # Errors
2111 ///
2112 /// This function will return an error in the following situations, but is not
2113 /// limited to just these cases:
2114 ///
2115 /// * The provided `path` doesn't exist.
2116 /// * The process lacks permissions to view the contents.
2117 /// * The `path` points at a non-directory file.
2118 ///
2119 /// # Examples
2120 ///
2121 /// ```
2122 /// use std::io;
2123 /// use std::fs::{self, DirEntry};
2124 /// use std::path::Path;
2125 ///
2126 /// // one possible implementation of walking a directory only visiting files
2127 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2128 ///     if dir.is_dir() {
2129 ///         for entry in fs::read_dir(dir)? {
2130 ///             let entry = entry?;
2131 ///             let path = entry.path();
2132 ///             if path.is_dir() {
2133 ///                 visit_dirs(&path, cb)?;
2134 ///             } else {
2135 ///                 cb(&entry);
2136 ///             }
2137 ///         }
2138 ///     }
2139 ///     Ok(())
2140 /// }
2141 /// ```
2142 ///
2143 /// ```rust,no_run
2144 /// use std::{fs, io};
2145 ///
2146 /// fn main() -> io::Result<()> {
2147 ///     let mut entries = fs::read_dir(".")?
2148 ///         .map(|res| res.map(|e| e.path()))
2149 ///         .collect::<Result<Vec<_>, io::Error>>()?;
2150 ///
2151 ///     // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2152 ///     // ordering is required the entries should be explicitly sorted.
2153 ///
2154 ///     entries.sort();
2155 ///
2156 ///     // The entries have now been sorted by their path.
2157 ///
2158 ///     Ok(())
2159 /// }
2160 /// ```
2161 #[stable(feature = "rust1", since = "1.0.0")]
2162 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2163     fs_imp::readdir(path.as_ref()).map(ReadDir)
2164 }
2165
2166 /// Changes the permissions found on a file or a directory.
2167 ///
2168 /// # Platform-specific behavior
2169 ///
2170 /// This function currently corresponds to the `chmod` function on Unix
2171 /// and the `SetFileAttributes` function on Windows.
2172 /// Note that, this [may change in the future][changes].
2173 ///
2174 /// [changes]: io#platform-specific-behavior
2175 ///
2176 /// # Errors
2177 ///
2178 /// This function will return an error in the following situations, but is not
2179 /// limited to just these cases:
2180 ///
2181 /// * `path` does not exist.
2182 /// * The user lacks the permission to change attributes of the file.
2183 ///
2184 /// # Examples
2185 ///
2186 /// ```no_run
2187 /// use std::fs;
2188 ///
2189 /// fn main() -> std::io::Result<()> {
2190 ///     let mut perms = fs::metadata("foo.txt")?.permissions();
2191 ///     perms.set_readonly(true);
2192 ///     fs::set_permissions("foo.txt", perms)?;
2193 ///     Ok(())
2194 /// }
2195 /// ```
2196 #[stable(feature = "set_permissions", since = "1.1.0")]
2197 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2198     fs_imp::set_perm(path.as_ref(), perm.0)
2199 }
2200
2201 impl DirBuilder {
2202     /// Creates a new set of options with default mode/security settings for all
2203     /// platforms and also non-recursive.
2204     ///
2205     /// # Examples
2206     ///
2207     /// ```
2208     /// use std::fs::DirBuilder;
2209     ///
2210     /// let builder = DirBuilder::new();
2211     /// ```
2212     #[stable(feature = "dir_builder", since = "1.6.0")]
2213     #[must_use]
2214     pub fn new() -> DirBuilder {
2215         DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2216     }
2217
2218     /// Indicates that directories should be created recursively, creating all
2219     /// parent directories. Parents that do not exist are created with the same
2220     /// security and permissions settings.
2221     ///
2222     /// This option defaults to `false`.
2223     ///
2224     /// # Examples
2225     ///
2226     /// ```
2227     /// use std::fs::DirBuilder;
2228     ///
2229     /// let mut builder = DirBuilder::new();
2230     /// builder.recursive(true);
2231     /// ```
2232     #[stable(feature = "dir_builder", since = "1.6.0")]
2233     pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2234         self.recursive = recursive;
2235         self
2236     }
2237
2238     /// Creates the specified directory with the options configured in this
2239     /// builder.
2240     ///
2241     /// It is considered an error if the directory already exists unless
2242     /// recursive mode is enabled.
2243     ///
2244     /// # Examples
2245     ///
2246     /// ```no_run
2247     /// use std::fs::{self, DirBuilder};
2248     ///
2249     /// let path = "/tmp/foo/bar/baz";
2250     /// DirBuilder::new()
2251     ///     .recursive(true)
2252     ///     .create(path).unwrap();
2253     ///
2254     /// assert!(fs::metadata(path).unwrap().is_dir());
2255     /// ```
2256     #[stable(feature = "dir_builder", since = "1.6.0")]
2257     pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2258         self._create(path.as_ref())
2259     }
2260
2261     fn _create(&self, path: &Path) -> io::Result<()> {
2262         if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2263     }
2264
2265     fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2266         if path == Path::new("") {
2267             return Ok(());
2268         }
2269
2270         match self.inner.mkdir(path) {
2271             Ok(()) => return Ok(()),
2272             Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2273             Err(_) if path.is_dir() => return Ok(()),
2274             Err(e) => return Err(e),
2275         }
2276         match path.parent() {
2277             Some(p) => self.create_dir_all(p)?,
2278             None => {
2279                 return Err(io::const_io_error!(
2280                     io::ErrorKind::Uncategorized,
2281                     "failed to create whole tree",
2282                 ));
2283             }
2284         }
2285         match self.inner.mkdir(path) {
2286             Ok(()) => Ok(()),
2287             Err(_) if path.is_dir() => Ok(()),
2288             Err(e) => Err(e),
2289         }
2290     }
2291 }
2292
2293 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2294     fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2295         &mut self.inner
2296     }
2297 }
2298
2299 /// Returns `Ok(true)` if the path points at an existing entity.
2300 ///
2301 /// This function will traverse symbolic links to query information about the
2302 /// destination file. In case of broken symbolic links this will return `Ok(false)`.
2303 ///
2304 /// As opposed to the [`Path::exists`] method, this one doesn't silently ignore errors
2305 /// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2306 /// denied on some of the parent directories.)
2307 ///
2308 /// # Examples
2309 ///
2310 /// ```no_run
2311 /// #![feature(path_try_exists)]
2312 /// use std::fs;
2313 ///
2314 /// assert!(!fs::try_exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
2315 /// assert!(fs::try_exists("/root/secret_file.txt").is_err());
2316 /// ```
2317 ///
2318 /// [`Path::exists`]: crate::path::Path::exists
2319 // FIXME: stabilization should modify documentation of `exists()` to recommend this method
2320 // instead.
2321 #[unstable(feature = "path_try_exists", issue = "83186")]
2322 #[inline]
2323 pub fn try_exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
2324     fs_imp::try_exists(path.as_ref())
2325 }