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