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