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