]> git.lizzy.rs Git - rust.git/blob - library/std/src/fs.rs
remove pat2021
[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 the size of the file, in bytes, this metadata is for.
1011     ///
1012     /// # Examples
1013     ///
1014     /// ```no_run
1015     /// use std::fs;
1016     ///
1017     /// fn main() -> std::io::Result<()> {
1018     ///     let metadata = fs::metadata("foo.txt")?;
1019     ///
1020     ///     assert_eq!(0, metadata.len());
1021     ///     Ok(())
1022     /// }
1023     /// ```
1024     #[stable(feature = "rust1", since = "1.0.0")]
1025     pub fn len(&self) -> u64 {
1026         self.0.size()
1027     }
1028
1029     /// Returns the permissions of the file this metadata is for.
1030     ///
1031     /// # Examples
1032     ///
1033     /// ```no_run
1034     /// use std::fs;
1035     ///
1036     /// fn main() -> std::io::Result<()> {
1037     ///     let metadata = fs::metadata("foo.txt")?;
1038     ///
1039     ///     assert!(!metadata.permissions().readonly());
1040     ///     Ok(())
1041     /// }
1042     /// ```
1043     #[stable(feature = "rust1", since = "1.0.0")]
1044     pub fn permissions(&self) -> Permissions {
1045         Permissions(self.0.perm())
1046     }
1047
1048     /// Returns the last modification time listed in this metadata.
1049     ///
1050     /// The returned value corresponds to the `mtime` field of `stat` on Unix
1051     /// platforms and the `ftLastWriteTime` field on Windows platforms.
1052     ///
1053     /// # Errors
1054     ///
1055     /// This field may not be available on all platforms, and will return an
1056     /// `Err` on platforms where it is not available.
1057     ///
1058     /// # Examples
1059     ///
1060     /// ```no_run
1061     /// use std::fs;
1062     ///
1063     /// fn main() -> std::io::Result<()> {
1064     ///     let metadata = fs::metadata("foo.txt")?;
1065     ///
1066     ///     if let Ok(time) = metadata.modified() {
1067     ///         println!("{:?}", time);
1068     ///     } else {
1069     ///         println!("Not supported on this platform");
1070     ///     }
1071     ///     Ok(())
1072     /// }
1073     /// ```
1074     #[stable(feature = "fs_time", since = "1.10.0")]
1075     pub fn modified(&self) -> io::Result<SystemTime> {
1076         self.0.modified().map(FromInner::from_inner)
1077     }
1078
1079     /// Returns the last access time of this metadata.
1080     ///
1081     /// The returned value corresponds to the `atime` field of `stat` on Unix
1082     /// platforms and the `ftLastAccessTime` field on Windows platforms.
1083     ///
1084     /// Note that not all platforms will keep this field update in a file's
1085     /// metadata, for example Windows has an option to disable updating this
1086     /// time when files are accessed and Linux similarly has `noatime`.
1087     ///
1088     /// # Errors
1089     ///
1090     /// This field may not be available on all platforms, and will return an
1091     /// `Err` on platforms where it is not available.
1092     ///
1093     /// # Examples
1094     ///
1095     /// ```no_run
1096     /// use std::fs;
1097     ///
1098     /// fn main() -> std::io::Result<()> {
1099     ///     let metadata = fs::metadata("foo.txt")?;
1100     ///
1101     ///     if let Ok(time) = metadata.accessed() {
1102     ///         println!("{:?}", time);
1103     ///     } else {
1104     ///         println!("Not supported on this platform");
1105     ///     }
1106     ///     Ok(())
1107     /// }
1108     /// ```
1109     #[stable(feature = "fs_time", since = "1.10.0")]
1110     pub fn accessed(&self) -> io::Result<SystemTime> {
1111         self.0.accessed().map(FromInner::from_inner)
1112     }
1113
1114     /// Returns the creation time listed in this metadata.
1115     ///
1116     /// The returned value corresponds to the `btime` field of `statx` on
1117     /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1118     /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1119     ///
1120     /// # Errors
1121     ///
1122     /// This field may not be available on all platforms, and will return an
1123     /// `Err` on platforms or filesystems where it is not available.
1124     ///
1125     /// # Examples
1126     ///
1127     /// ```no_run
1128     /// use std::fs;
1129     ///
1130     /// fn main() -> std::io::Result<()> {
1131     ///     let metadata = fs::metadata("foo.txt")?;
1132     ///
1133     ///     if let Ok(time) = metadata.created() {
1134     ///         println!("{:?}", time);
1135     ///     } else {
1136     ///         println!("Not supported on this platform or filesystem");
1137     ///     }
1138     ///     Ok(())
1139     /// }
1140     /// ```
1141     #[stable(feature = "fs_time", since = "1.10.0")]
1142     pub fn created(&self) -> io::Result<SystemTime> {
1143         self.0.created().map(FromInner::from_inner)
1144     }
1145 }
1146
1147 #[stable(feature = "std_debug", since = "1.16.0")]
1148 impl fmt::Debug for Metadata {
1149     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1150         f.debug_struct("Metadata")
1151             .field("file_type", &self.file_type())
1152             .field("is_dir", &self.is_dir())
1153             .field("is_file", &self.is_file())
1154             .field("permissions", &self.permissions())
1155             .field("modified", &self.modified())
1156             .field("accessed", &self.accessed())
1157             .field("created", &self.created())
1158             .finish_non_exhaustive()
1159     }
1160 }
1161
1162 impl AsInner<fs_imp::FileAttr> for Metadata {
1163     fn as_inner(&self) -> &fs_imp::FileAttr {
1164         &self.0
1165     }
1166 }
1167
1168 impl FromInner<fs_imp::FileAttr> for Metadata {
1169     fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1170         Metadata(attr)
1171     }
1172 }
1173
1174 impl Permissions {
1175     /// Returns `true` if these permissions describe a readonly (unwritable) file.
1176     ///
1177     /// # Examples
1178     ///
1179     /// ```no_run
1180     /// use std::fs::File;
1181     ///
1182     /// fn main() -> std::io::Result<()> {
1183     ///     let mut f = File::create("foo.txt")?;
1184     ///     let metadata = f.metadata()?;
1185     ///
1186     ///     assert_eq!(false, metadata.permissions().readonly());
1187     ///     Ok(())
1188     /// }
1189     /// ```
1190     #[stable(feature = "rust1", since = "1.0.0")]
1191     pub fn readonly(&self) -> bool {
1192         self.0.readonly()
1193     }
1194
1195     /// Modifies the readonly flag for this set of permissions. If the
1196     /// `readonly` argument is `true`, using the resulting `Permission` will
1197     /// update file permissions to forbid writing. Conversely, if it's `false`,
1198     /// using the resulting `Permission` will update file permissions to allow
1199     /// writing.
1200     ///
1201     /// This operation does **not** modify the filesystem. To modify the
1202     /// filesystem use the [`set_permissions`] function.
1203     ///
1204     /// # Examples
1205     ///
1206     /// ```no_run
1207     /// use std::fs::File;
1208     ///
1209     /// fn main() -> std::io::Result<()> {
1210     ///     let f = File::create("foo.txt")?;
1211     ///     let metadata = f.metadata()?;
1212     ///     let mut permissions = metadata.permissions();
1213     ///
1214     ///     permissions.set_readonly(true);
1215     ///
1216     ///     // filesystem doesn't change
1217     ///     assert_eq!(false, metadata.permissions().readonly());
1218     ///
1219     ///     // just this particular `permissions`.
1220     ///     assert_eq!(true, permissions.readonly());
1221     ///     Ok(())
1222     /// }
1223     /// ```
1224     #[stable(feature = "rust1", since = "1.0.0")]
1225     pub fn set_readonly(&mut self, readonly: bool) {
1226         self.0.set_readonly(readonly)
1227     }
1228 }
1229
1230 impl FileType {
1231     /// Tests whether this file type represents a directory. The
1232     /// result is mutually exclusive to the results of
1233     /// [`is_file`] and [`is_symlink`]; only zero or one of these
1234     /// tests may pass.
1235     ///
1236     /// [`is_file`]: FileType::is_file
1237     /// [`is_symlink`]: FileType::is_symlink
1238     ///
1239     /// # Examples
1240     ///
1241     /// ```no_run
1242     /// fn main() -> std::io::Result<()> {
1243     ///     use std::fs;
1244     ///
1245     ///     let metadata = fs::metadata("foo.txt")?;
1246     ///     let file_type = metadata.file_type();
1247     ///
1248     ///     assert_eq!(file_type.is_dir(), false);
1249     ///     Ok(())
1250     /// }
1251     /// ```
1252     #[stable(feature = "file_type", since = "1.1.0")]
1253     pub fn is_dir(&self) -> bool {
1254         self.0.is_dir()
1255     }
1256
1257     /// Tests whether this file type represents a regular file.
1258     /// The result is  mutually exclusive to the results of
1259     /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1260     /// tests may pass.
1261     ///
1262     /// When the goal is simply to read from (or write to) the source, the most
1263     /// reliable way to test the source can be read (or written to) is to open
1264     /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1265     /// a Unix-like system for example. See [`File::open`] or
1266     /// [`OpenOptions::open`] for more information.
1267     ///
1268     /// [`is_dir`]: FileType::is_dir
1269     /// [`is_symlink`]: FileType::is_symlink
1270     ///
1271     /// # Examples
1272     ///
1273     /// ```no_run
1274     /// fn main() -> std::io::Result<()> {
1275     ///     use std::fs;
1276     ///
1277     ///     let metadata = fs::metadata("foo.txt")?;
1278     ///     let file_type = metadata.file_type();
1279     ///
1280     ///     assert_eq!(file_type.is_file(), true);
1281     ///     Ok(())
1282     /// }
1283     /// ```
1284     #[stable(feature = "file_type", since = "1.1.0")]
1285     pub fn is_file(&self) -> bool {
1286         self.0.is_file()
1287     }
1288
1289     /// Tests whether this file type represents a symbolic link.
1290     /// The result is mutually exclusive to the results of
1291     /// [`is_dir`] and [`is_file`]; only zero or one of these
1292     /// tests may pass.
1293     ///
1294     /// The underlying [`Metadata`] struct needs to be retrieved
1295     /// with the [`fs::symlink_metadata`] function and not the
1296     /// [`fs::metadata`] function. The [`fs::metadata`] function
1297     /// follows symbolic links, so [`is_symlink`] would always
1298     /// return `false` for the target file.
1299     ///
1300     /// [`fs::metadata`]: metadata
1301     /// [`fs::symlink_metadata`]: symlink_metadata
1302     /// [`is_dir`]: FileType::is_dir
1303     /// [`is_file`]: FileType::is_file
1304     /// [`is_symlink`]: FileType::is_symlink
1305     ///
1306     /// # Examples
1307     ///
1308     /// ```no_run
1309     /// use std::fs;
1310     ///
1311     /// fn main() -> std::io::Result<()> {
1312     ///     let metadata = fs::symlink_metadata("foo.txt")?;
1313     ///     let file_type = metadata.file_type();
1314     ///
1315     ///     assert_eq!(file_type.is_symlink(), false);
1316     ///     Ok(())
1317     /// }
1318     /// ```
1319     #[stable(feature = "file_type", since = "1.1.0")]
1320     pub fn is_symlink(&self) -> bool {
1321         self.0.is_symlink()
1322     }
1323 }
1324
1325 impl AsInner<fs_imp::FileType> for FileType {
1326     fn as_inner(&self) -> &fs_imp::FileType {
1327         &self.0
1328     }
1329 }
1330
1331 impl FromInner<fs_imp::FilePermissions> for Permissions {
1332     fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1333         Permissions(f)
1334     }
1335 }
1336
1337 impl AsInner<fs_imp::FilePermissions> for Permissions {
1338     fn as_inner(&self) -> &fs_imp::FilePermissions {
1339         &self.0
1340     }
1341 }
1342
1343 #[stable(feature = "rust1", since = "1.0.0")]
1344 impl Iterator for ReadDir {
1345     type Item = io::Result<DirEntry>;
1346
1347     fn next(&mut self) -> Option<io::Result<DirEntry>> {
1348         self.0.next().map(|entry| entry.map(DirEntry))
1349     }
1350 }
1351
1352 impl DirEntry {
1353     /// Returns the full path to the file that this entry represents.
1354     ///
1355     /// The full path is created by joining the original path to `read_dir`
1356     /// with the filename of this entry.
1357     ///
1358     /// # Examples
1359     ///
1360     /// ```no_run
1361     /// use std::fs;
1362     ///
1363     /// fn main() -> std::io::Result<()> {
1364     ///     for entry in fs::read_dir(".")? {
1365     ///         let dir = entry?;
1366     ///         println!("{:?}", dir.path());
1367     ///     }
1368     ///     Ok(())
1369     /// }
1370     /// ```
1371     ///
1372     /// This prints output like:
1373     ///
1374     /// ```text
1375     /// "./whatever.txt"
1376     /// "./foo.html"
1377     /// "./hello_world.rs"
1378     /// ```
1379     ///
1380     /// The exact text, of course, depends on what files you have in `.`.
1381     #[stable(feature = "rust1", since = "1.0.0")]
1382     pub fn path(&self) -> PathBuf {
1383         self.0.path()
1384     }
1385
1386     /// Returns the metadata for the file that this entry points at.
1387     ///
1388     /// This function will not traverse symlinks if this entry points at a
1389     /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1390     ///
1391     /// [`fs::metadata`]: metadata
1392     /// [`fs::File::metadata`]: File::metadata
1393     ///
1394     /// # Platform-specific behavior
1395     ///
1396     /// On Windows this function is cheap to call (no extra system calls
1397     /// needed), but on Unix platforms this function is the equivalent of
1398     /// calling `symlink_metadata` on the path.
1399     ///
1400     /// # Examples
1401     ///
1402     /// ```
1403     /// use std::fs;
1404     ///
1405     /// if let Ok(entries) = fs::read_dir(".") {
1406     ///     for entry in entries {
1407     ///         if let Ok(entry) = entry {
1408     ///             // Here, `entry` is a `DirEntry`.
1409     ///             if let Ok(metadata) = entry.metadata() {
1410     ///                 // Now let's show our entry's permissions!
1411     ///                 println!("{:?}: {:?}", entry.path(), metadata.permissions());
1412     ///             } else {
1413     ///                 println!("Couldn't get metadata for {:?}", entry.path());
1414     ///             }
1415     ///         }
1416     ///     }
1417     /// }
1418     /// ```
1419     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1420     pub fn metadata(&self) -> io::Result<Metadata> {
1421         self.0.metadata().map(Metadata)
1422     }
1423
1424     /// Returns the file type for the file that this entry points at.
1425     ///
1426     /// This function will not traverse symlinks if this entry points at a
1427     /// symlink.
1428     ///
1429     /// # Platform-specific behavior
1430     ///
1431     /// On Windows and most Unix platforms this function is free (no extra
1432     /// system calls needed), but some Unix platforms may require the equivalent
1433     /// call to `symlink_metadata` to learn about the target file type.
1434     ///
1435     /// # Examples
1436     ///
1437     /// ```
1438     /// use std::fs;
1439     ///
1440     /// if let Ok(entries) = fs::read_dir(".") {
1441     ///     for entry in entries {
1442     ///         if let Ok(entry) = entry {
1443     ///             // Here, `entry` is a `DirEntry`.
1444     ///             if let Ok(file_type) = entry.file_type() {
1445     ///                 // Now let's show our entry's file type!
1446     ///                 println!("{:?}: {:?}", entry.path(), file_type);
1447     ///             } else {
1448     ///                 println!("Couldn't get file type for {:?}", entry.path());
1449     ///             }
1450     ///         }
1451     ///     }
1452     /// }
1453     /// ```
1454     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1455     pub fn file_type(&self) -> io::Result<FileType> {
1456         self.0.file_type().map(FileType)
1457     }
1458
1459     /// Returns the bare file name of this directory entry without any other
1460     /// leading path component.
1461     ///
1462     /// # Examples
1463     ///
1464     /// ```
1465     /// use std::fs;
1466     ///
1467     /// if let Ok(entries) = fs::read_dir(".") {
1468     ///     for entry in entries {
1469     ///         if let Ok(entry) = entry {
1470     ///             // Here, `entry` is a `DirEntry`.
1471     ///             println!("{:?}", entry.file_name());
1472     ///         }
1473     ///     }
1474     /// }
1475     /// ```
1476     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1477     pub fn file_name(&self) -> OsString {
1478         self.0.file_name()
1479     }
1480 }
1481
1482 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1483 impl fmt::Debug for DirEntry {
1484     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1485         f.debug_tuple("DirEntry").field(&self.path()).finish()
1486     }
1487 }
1488
1489 impl AsInner<fs_imp::DirEntry> for DirEntry {
1490     fn as_inner(&self) -> &fs_imp::DirEntry {
1491         &self.0
1492     }
1493 }
1494
1495 /// Removes a file from the filesystem.
1496 ///
1497 /// Note that there is no
1498 /// guarantee that the file is immediately deleted (e.g., depending on
1499 /// platform, other open file descriptors may prevent immediate removal).
1500 ///
1501 /// # Platform-specific behavior
1502 ///
1503 /// This function currently corresponds to the `unlink` function on Unix
1504 /// and the `DeleteFile` function on Windows.
1505 /// Note that, this [may change in the future][changes].
1506 ///
1507 /// [changes]: io#platform-specific-behavior
1508 ///
1509 /// # Errors
1510 ///
1511 /// This function will return an error in the following situations, but is not
1512 /// limited to just these cases:
1513 ///
1514 /// * `path` points to a directory.
1515 /// * The file doesn't exist.
1516 /// * The user lacks permissions to remove the file.
1517 ///
1518 /// # Examples
1519 ///
1520 /// ```no_run
1521 /// use std::fs;
1522 ///
1523 /// fn main() -> std::io::Result<()> {
1524 ///     fs::remove_file("a.txt")?;
1525 ///     Ok(())
1526 /// }
1527 /// ```
1528 #[doc(alias = "delete")]
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1531     fs_imp::unlink(path.as_ref())
1532 }
1533
1534 /// Given a path, query the file system to get information about a file,
1535 /// directory, etc.
1536 ///
1537 /// This function will traverse symbolic links to query information about the
1538 /// destination file.
1539 ///
1540 /// # Platform-specific behavior
1541 ///
1542 /// This function currently corresponds to the `stat` function on Unix
1543 /// and the `GetFileAttributesEx` function on Windows.
1544 /// Note that, this [may change in the future][changes].
1545 ///
1546 /// [changes]: io#platform-specific-behavior
1547 ///
1548 /// # Errors
1549 ///
1550 /// This function will return an error in the following situations, but is not
1551 /// limited to just these cases:
1552 ///
1553 /// * The user lacks permissions to perform `metadata` call on `path`.
1554 /// * `path` does not exist.
1555 ///
1556 /// # Examples
1557 ///
1558 /// ```rust,no_run
1559 /// use std::fs;
1560 ///
1561 /// fn main() -> std::io::Result<()> {
1562 ///     let attr = fs::metadata("/some/file/path.txt")?;
1563 ///     // inspect attr ...
1564 ///     Ok(())
1565 /// }
1566 /// ```
1567 #[stable(feature = "rust1", since = "1.0.0")]
1568 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1569     fs_imp::stat(path.as_ref()).map(Metadata)
1570 }
1571
1572 /// Query the metadata about a file without following symlinks.
1573 ///
1574 /// # Platform-specific behavior
1575 ///
1576 /// This function currently corresponds to the `lstat` function on Unix
1577 /// and the `GetFileAttributesEx` function on Windows.
1578 /// Note that, this [may change in the future][changes].
1579 ///
1580 /// [changes]: io#platform-specific-behavior
1581 ///
1582 /// # Errors
1583 ///
1584 /// This function will return an error in the following situations, but is not
1585 /// limited to just these cases:
1586 ///
1587 /// * The user lacks permissions to perform `metadata` call on `path`.
1588 /// * `path` does not exist.
1589 ///
1590 /// # Examples
1591 ///
1592 /// ```rust,no_run
1593 /// use std::fs;
1594 ///
1595 /// fn main() -> std::io::Result<()> {
1596 ///     let attr = fs::symlink_metadata("/some/file/path.txt")?;
1597 ///     // inspect attr ...
1598 ///     Ok(())
1599 /// }
1600 /// ```
1601 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1602 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1603     fs_imp::lstat(path.as_ref()).map(Metadata)
1604 }
1605
1606 /// Rename a file or directory to a new name, replacing the original file if
1607 /// `to` already exists.
1608 ///
1609 /// This will not work if the new name is on a different mount point.
1610 ///
1611 /// # Platform-specific behavior
1612 ///
1613 /// This function currently corresponds to the `rename` function on Unix
1614 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1615 ///
1616 /// Because of this, the behavior when both `from` and `to` exist differs. On
1617 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1618 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1619 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1620 ///
1621 /// Note that, this [may change in the future][changes].
1622 ///
1623 /// [changes]: io#platform-specific-behavior
1624 ///
1625 /// # Errors
1626 ///
1627 /// This function will return an error in the following situations, but is not
1628 /// limited to just these cases:
1629 ///
1630 /// * `from` does not exist.
1631 /// * The user lacks permissions to view contents.
1632 /// * `from` and `to` are on separate filesystems.
1633 ///
1634 /// # Examples
1635 ///
1636 /// ```no_run
1637 /// use std::fs;
1638 ///
1639 /// fn main() -> std::io::Result<()> {
1640 ///     fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1641 ///     Ok(())
1642 /// }
1643 /// ```
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1646     fs_imp::rename(from.as_ref(), to.as_ref())
1647 }
1648
1649 /// Copies the contents of one file to another. This function will also
1650 /// copy the permission bits of the original file to the destination file.
1651 ///
1652 /// This function will **overwrite** the contents of `to`.
1653 ///
1654 /// Note that if `from` and `to` both point to the same file, then the file
1655 /// will likely get truncated by this operation.
1656 ///
1657 /// On success, the total number of bytes copied is returned and it is equal to
1658 /// the length of the `to` file as reported by `metadata`.
1659 ///
1660 /// If you’re wanting to copy the contents of one file to another and you’re
1661 /// working with [`File`]s, see the [`io::copy()`] function.
1662 ///
1663 /// # Platform-specific behavior
1664 ///
1665 /// This function currently corresponds to the `open` function in Unix
1666 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1667 /// `O_CLOEXEC` is set for returned file descriptors.
1668 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1669 /// NTFS streams are copied but only the size of the main stream is returned by
1670 /// this function. On MacOS, this function corresponds to `fclonefileat` and
1671 /// `fcopyfile`.
1672 /// Note that, this [may change in the future][changes].
1673 ///
1674 /// [changes]: io#platform-specific-behavior
1675 ///
1676 /// # Errors
1677 ///
1678 /// This function will return an error in the following situations, but is not
1679 /// limited to just these cases:
1680 ///
1681 /// * `from` is neither a regular file nor a symlink to a regular file.
1682 /// * `from` does not exist.
1683 /// * The current process does not have the permission rights to read
1684 ///   `from` or write `to`.
1685 ///
1686 /// # Examples
1687 ///
1688 /// ```no_run
1689 /// use std::fs;
1690 ///
1691 /// fn main() -> std::io::Result<()> {
1692 ///     fs::copy("foo.txt", "bar.txt")?;  // Copy foo.txt to bar.txt
1693 ///     Ok(())
1694 /// }
1695 /// ```
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1698     fs_imp::copy(from.as_ref(), to.as_ref())
1699 }
1700
1701 /// Creates a new hard link on the filesystem.
1702 ///
1703 /// The `link` path will be a link pointing to the `original` path. Note that
1704 /// systems often require these two paths to both be located on the same
1705 /// filesystem.
1706 ///
1707 /// If `original` names a symbolic link, it is platform-specific whether the
1708 /// symbolic link is followed. On platforms where it's possible to not follow
1709 /// it, it is not followed, and the created hard link points to the symbolic
1710 /// link itself.
1711 ///
1712 /// # Platform-specific behavior
1713 ///
1714 /// This function currently corresponds to the `linkat` function with no flags
1715 /// on Unix and the `CreateHardLink` function on Windows.
1716 /// Note that, this [may change in the future][changes].
1717 ///
1718 /// [changes]: io#platform-specific-behavior
1719 ///
1720 /// # Errors
1721 ///
1722 /// This function will return an error in the following situations, but is not
1723 /// limited to just these cases:
1724 ///
1725 /// * The `original` path is not a file or doesn't exist.
1726 ///
1727 /// # Examples
1728 ///
1729 /// ```no_run
1730 /// use std::fs;
1731 ///
1732 /// fn main() -> std::io::Result<()> {
1733 ///     fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1734 ///     Ok(())
1735 /// }
1736 /// ```
1737 #[stable(feature = "rust1", since = "1.0.0")]
1738 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1739     fs_imp::link(original.as_ref(), link.as_ref())
1740 }
1741
1742 /// Creates a new symbolic link on the filesystem.
1743 ///
1744 /// The `link` path will be a symbolic link pointing to the `original` path.
1745 /// On Windows, this will be a file symlink, not a directory symlink;
1746 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1747 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1748 /// used instead to make the intent explicit.
1749 ///
1750 /// [`std::os::unix::fs::symlink`]: crate::os::unix::fs::symlink
1751 /// [`std::os::windows::fs::symlink_file`]: crate::os::windows::fs::symlink_file
1752 /// [`symlink_dir`]: crate::os::windows::fs::symlink_dir
1753 ///
1754 /// # Examples
1755 ///
1756 /// ```no_run
1757 /// use std::fs;
1758 ///
1759 /// fn main() -> std::io::Result<()> {
1760 ///     fs::soft_link("a.txt", "b.txt")?;
1761 ///     Ok(())
1762 /// }
1763 /// ```
1764 #[stable(feature = "rust1", since = "1.0.0")]
1765 #[rustc_deprecated(
1766     since = "1.1.0",
1767     reason = "replaced with std::os::unix::fs::symlink and \
1768               std::os::windows::fs::{symlink_file, symlink_dir}"
1769 )]
1770 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(original: P, link: Q) -> io::Result<()> {
1771     fs_imp::symlink(original.as_ref(), link.as_ref())
1772 }
1773
1774 /// Reads a symbolic link, returning the file that the link points to.
1775 ///
1776 /// # Platform-specific behavior
1777 ///
1778 /// This function currently corresponds to the `readlink` function on Unix
1779 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1780 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1781 /// Note that, this [may change in the future][changes].
1782 ///
1783 /// [changes]: io#platform-specific-behavior
1784 ///
1785 /// # Errors
1786 ///
1787 /// This function will return an error in the following situations, but is not
1788 /// limited to just these cases:
1789 ///
1790 /// * `path` is not a symbolic link.
1791 /// * `path` does not exist.
1792 ///
1793 /// # Examples
1794 ///
1795 /// ```no_run
1796 /// use std::fs;
1797 ///
1798 /// fn main() -> std::io::Result<()> {
1799 ///     let path = fs::read_link("a.txt")?;
1800 ///     Ok(())
1801 /// }
1802 /// ```
1803 #[stable(feature = "rust1", since = "1.0.0")]
1804 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1805     fs_imp::readlink(path.as_ref())
1806 }
1807
1808 /// Returns the canonical, absolute form of a path with all intermediate
1809 /// components normalized and symbolic links resolved.
1810 ///
1811 /// # Platform-specific behavior
1812 ///
1813 /// This function currently corresponds to the `realpath` function on Unix
1814 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1815 /// Note that, this [may change in the future][changes].
1816 ///
1817 /// On Windows, this converts the path to use [extended length path][path]
1818 /// syntax, which allows your program to use longer path names, but means you
1819 /// can only join backslash-delimited paths to it, and it may be incompatible
1820 /// with other applications (if passed to the application on the command-line,
1821 /// or written to a file another application may read).
1822 ///
1823 /// [changes]: io#platform-specific-behavior
1824 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1825 ///
1826 /// # Errors
1827 ///
1828 /// This function will return an error in the following situations, but is not
1829 /// limited to just these cases:
1830 ///
1831 /// * `path` does not exist.
1832 /// * A non-final component in path is not a directory.
1833 ///
1834 /// # Examples
1835 ///
1836 /// ```no_run
1837 /// use std::fs;
1838 ///
1839 /// fn main() -> std::io::Result<()> {
1840 ///     let path = fs::canonicalize("../a/../foo.txt")?;
1841 ///     Ok(())
1842 /// }
1843 /// ```
1844 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1845 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1846     fs_imp::canonicalize(path.as_ref())
1847 }
1848
1849 /// Creates a new, empty directory at the provided path
1850 ///
1851 /// # Platform-specific behavior
1852 ///
1853 /// This function currently corresponds to the `mkdir` function on Unix
1854 /// and the `CreateDirectory` function on Windows.
1855 /// Note that, this [may change in the future][changes].
1856 ///
1857 /// [changes]: io#platform-specific-behavior
1858 ///
1859 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1860 /// return an error. To create a directory and all its missing parents at the
1861 /// same time, use the [`create_dir_all`] function.
1862 ///
1863 /// # Errors
1864 ///
1865 /// This function will return an error in the following situations, but is not
1866 /// limited to just these cases:
1867 ///
1868 /// * User lacks permissions to create directory at `path`.
1869 /// * A parent of the given path doesn't exist. (To create a directory and all
1870 ///   its missing parents at the same time, use the [`create_dir_all`]
1871 ///   function.)
1872 /// * `path` already exists.
1873 ///
1874 /// # Examples
1875 ///
1876 /// ```no_run
1877 /// use std::fs;
1878 ///
1879 /// fn main() -> std::io::Result<()> {
1880 ///     fs::create_dir("/some/dir")?;
1881 ///     Ok(())
1882 /// }
1883 /// ```
1884 #[stable(feature = "rust1", since = "1.0.0")]
1885 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1886     DirBuilder::new().create(path.as_ref())
1887 }
1888
1889 /// Recursively create a directory and all of its parent components if they
1890 /// are missing.
1891 ///
1892 /// # Platform-specific behavior
1893 ///
1894 /// This function currently corresponds to the `mkdir` function on Unix
1895 /// and the `CreateDirectory` function on Windows.
1896 /// Note that, this [may change in the future][changes].
1897 ///
1898 /// [changes]: io#platform-specific-behavior
1899 ///
1900 /// # Errors
1901 ///
1902 /// This function will return an error in the following situations, but is not
1903 /// limited to just these cases:
1904 ///
1905 /// * If any directory in the path specified by `path`
1906 /// does not already exist and it could not be created otherwise. The specific
1907 /// error conditions for when a directory is being created (after it is
1908 /// determined to not exist) are outlined by [`fs::create_dir`].
1909 ///
1910 /// Notable exception is made for situations where any of the directories
1911 /// specified in the `path` could not be created as it was being created concurrently.
1912 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1913 /// concurrently from multiple threads or processes is guaranteed not to fail
1914 /// due to a race condition with itself.
1915 ///
1916 /// [`fs::create_dir`]: create_dir
1917 ///
1918 /// # Examples
1919 ///
1920 /// ```no_run
1921 /// use std::fs;
1922 ///
1923 /// fn main() -> std::io::Result<()> {
1924 ///     fs::create_dir_all("/some/dir")?;
1925 ///     Ok(())
1926 /// }
1927 /// ```
1928 #[stable(feature = "rust1", since = "1.0.0")]
1929 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1930     DirBuilder::new().recursive(true).create(path.as_ref())
1931 }
1932
1933 /// Removes an empty directory.
1934 ///
1935 /// # Platform-specific behavior
1936 ///
1937 /// This function currently corresponds to the `rmdir` function on Unix
1938 /// and the `RemoveDirectory` function on Windows.
1939 /// Note that, this [may change in the future][changes].
1940 ///
1941 /// [changes]: io#platform-specific-behavior
1942 ///
1943 /// # Errors
1944 ///
1945 /// This function will return an error in the following situations, but is not
1946 /// limited to just these cases:
1947 ///
1948 /// * `path` doesn't exist.
1949 /// * `path` isn't a directory.
1950 /// * The user lacks permissions to remove the directory at the provided `path`.
1951 /// * The directory isn't empty.
1952 ///
1953 /// # Examples
1954 ///
1955 /// ```no_run
1956 /// use std::fs;
1957 ///
1958 /// fn main() -> std::io::Result<()> {
1959 ///     fs::remove_dir("/some/dir")?;
1960 ///     Ok(())
1961 /// }
1962 /// ```
1963 #[doc(alias = "delete")]
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1966     fs_imp::rmdir(path.as_ref())
1967 }
1968
1969 /// Removes a directory at this path, after removing all its contents. Use
1970 /// carefully!
1971 ///
1972 /// This function does **not** follow symbolic links and it will simply remove the
1973 /// symbolic link itself.
1974 ///
1975 /// # Platform-specific behavior
1976 ///
1977 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1978 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1979 /// on Windows.
1980 /// Note that, this [may change in the future][changes].
1981 ///
1982 /// [changes]: io#platform-specific-behavior
1983 ///
1984 /// # Errors
1985 ///
1986 /// See [`fs::remove_file`] and [`fs::remove_dir`].
1987 ///
1988 /// [`fs::remove_file`]: remove_file
1989 /// [`fs::remove_dir`]: remove_dir
1990 ///
1991 /// # Examples
1992 ///
1993 /// ```no_run
1994 /// use std::fs;
1995 ///
1996 /// fn main() -> std::io::Result<()> {
1997 ///     fs::remove_dir_all("/some/dir")?;
1998 ///     Ok(())
1999 /// }
2000 /// ```
2001 #[doc(alias = "delete")]
2002 #[stable(feature = "rust1", since = "1.0.0")]
2003 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2004     fs_imp::remove_dir_all(path.as_ref())
2005 }
2006
2007 /// Returns an iterator over the entries within a directory.
2008 ///
2009 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
2010 /// New errors may be encountered after an iterator is initially constructed.
2011 ///
2012 /// # Platform-specific behavior
2013 ///
2014 /// This function currently corresponds to the `opendir` function on Unix
2015 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2016 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2017 /// Note that, this [may change in the future][changes].
2018 ///
2019 /// [changes]: io#platform-specific-behavior
2020 ///
2021 /// The order in which this iterator returns entries is platform and filesystem
2022 /// dependent.
2023 ///
2024 /// # Errors
2025 ///
2026 /// This function will return an error in the following situations, but is not
2027 /// limited to just these cases:
2028 ///
2029 /// * The provided `path` doesn't exist.
2030 /// * The process lacks permissions to view the contents.
2031 /// * The `path` points at a non-directory file.
2032 ///
2033 /// # Examples
2034 ///
2035 /// ```
2036 /// use std::io;
2037 /// use std::fs::{self, DirEntry};
2038 /// use std::path::Path;
2039 ///
2040 /// // one possible implementation of walking a directory only visiting files
2041 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2042 ///     if dir.is_dir() {
2043 ///         for entry in fs::read_dir(dir)? {
2044 ///             let entry = entry?;
2045 ///             let path = entry.path();
2046 ///             if path.is_dir() {
2047 ///                 visit_dirs(&path, cb)?;
2048 ///             } else {
2049 ///                 cb(&entry);
2050 ///             }
2051 ///         }
2052 ///     }
2053 ///     Ok(())
2054 /// }
2055 /// ```
2056 ///
2057 /// ```rust,no_run
2058 /// use std::{fs, io};
2059 ///
2060 /// fn main() -> io::Result<()> {
2061 ///     let mut entries = fs::read_dir(".")?
2062 ///         .map(|res| res.map(|e| e.path()))
2063 ///         .collect::<Result<Vec<_>, io::Error>>()?;
2064 ///
2065 ///     // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2066 ///     // ordering is required the entries should be explicitly sorted.
2067 ///
2068 ///     entries.sort();
2069 ///
2070 ///     // The entries have now been sorted by their path.
2071 ///
2072 ///     Ok(())
2073 /// }
2074 /// ```
2075 #[stable(feature = "rust1", since = "1.0.0")]
2076 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2077     fs_imp::readdir(path.as_ref()).map(ReadDir)
2078 }
2079
2080 /// Changes the permissions found on a file or a directory.
2081 ///
2082 /// # Platform-specific behavior
2083 ///
2084 /// This function currently corresponds to the `chmod` function on Unix
2085 /// and the `SetFileAttributes` function on Windows.
2086 /// Note that, this [may change in the future][changes].
2087 ///
2088 /// [changes]: io#platform-specific-behavior
2089 ///
2090 /// # Errors
2091 ///
2092 /// This function will return an error in the following situations, but is not
2093 /// limited to just these cases:
2094 ///
2095 /// * `path` does not exist.
2096 /// * The user lacks the permission to change attributes of the file.
2097 ///
2098 /// # Examples
2099 ///
2100 /// ```no_run
2101 /// use std::fs;
2102 ///
2103 /// fn main() -> std::io::Result<()> {
2104 ///     let mut perms = fs::metadata("foo.txt")?.permissions();
2105 ///     perms.set_readonly(true);
2106 ///     fs::set_permissions("foo.txt", perms)?;
2107 ///     Ok(())
2108 /// }
2109 /// ```
2110 #[stable(feature = "set_permissions", since = "1.1.0")]
2111 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2112     fs_imp::set_perm(path.as_ref(), perm.0)
2113 }
2114
2115 impl DirBuilder {
2116     /// Creates a new set of options with default mode/security settings for all
2117     /// platforms and also non-recursive.
2118     ///
2119     /// # Examples
2120     ///
2121     /// ```
2122     /// use std::fs::DirBuilder;
2123     ///
2124     /// let builder = DirBuilder::new();
2125     /// ```
2126     #[stable(feature = "dir_builder", since = "1.6.0")]
2127     pub fn new() -> DirBuilder {
2128         DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2129     }
2130
2131     /// Indicates that directories should be created recursively, creating all
2132     /// parent directories. Parents that do not exist are created with the same
2133     /// security and permissions settings.
2134     ///
2135     /// This option defaults to `false`.
2136     ///
2137     /// # Examples
2138     ///
2139     /// ```
2140     /// use std::fs::DirBuilder;
2141     ///
2142     /// let mut builder = DirBuilder::new();
2143     /// builder.recursive(true);
2144     /// ```
2145     #[stable(feature = "dir_builder", since = "1.6.0")]
2146     pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2147         self.recursive = recursive;
2148         self
2149     }
2150
2151     /// Creates the specified directory with the options configured in this
2152     /// builder.
2153     ///
2154     /// It is considered an error if the directory already exists unless
2155     /// recursive mode is enabled.
2156     ///
2157     /// # Examples
2158     ///
2159     /// ```no_run
2160     /// use std::fs::{self, DirBuilder};
2161     ///
2162     /// let path = "/tmp/foo/bar/baz";
2163     /// DirBuilder::new()
2164     ///     .recursive(true)
2165     ///     .create(path).unwrap();
2166     ///
2167     /// assert!(fs::metadata(path).unwrap().is_dir());
2168     /// ```
2169     #[stable(feature = "dir_builder", since = "1.6.0")]
2170     pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2171         self._create(path.as_ref())
2172     }
2173
2174     fn _create(&self, path: &Path) -> io::Result<()> {
2175         if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2176     }
2177
2178     fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2179         if path == Path::new("") {
2180             return Ok(());
2181         }
2182
2183         match self.inner.mkdir(path) {
2184             Ok(()) => return Ok(()),
2185             Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2186             Err(_) if path.is_dir() => return Ok(()),
2187             Err(e) => return Err(e),
2188         }
2189         match path.parent() {
2190             Some(p) => self.create_dir_all(p)?,
2191             None => {
2192                 return Err(io::Error::new_const(
2193                     io::ErrorKind::Other,
2194                     &"failed to create whole tree",
2195                 ));
2196             }
2197         }
2198         match self.inner.mkdir(path) {
2199             Ok(()) => Ok(()),
2200             Err(_) if path.is_dir() => Ok(()),
2201             Err(e) => Err(e),
2202         }
2203     }
2204 }
2205
2206 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2207     fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2208         &mut self.inner
2209     }
2210 }