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