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