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