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