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