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