]> git.lizzy.rs Git - rust.git/blob - library/std/src/fs.rs
Update `fs::remove_file` docs
[rust.git] / library / std / src / fs.rs
1 // ignore-tidy-filelength
2
3 //! Filesystem manipulation operations.
4 //!
5 //! This module contains basic methods to manipulate the contents of the local
6 //! filesystem. All methods in this module represent cross-platform filesystem
7 //! operations. Extra platform-specific functionality can be found in the
8 //! extension traits of `std::os::$platform`.
9
10 #![stable(feature = "rust1", since = "1.0.0")]
11 #![deny(unsafe_op_in_unsafe_fn)]
12
13 use crate::ffi::OsString;
14 use crate::fmt;
15 use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
16 use crate::path::{Path, PathBuf};
17 use crate::sys::fs as fs_imp;
18 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
19 use crate::time::SystemTime;
20
21 /// A reference to an open file on the filesystem.
22 ///
23 /// An instance of a `File` can be read and/or written depending on what options
24 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
25 /// that the file contains internally.
26 ///
27 /// Files are automatically closed when they go out of scope.  Errors detected
28 /// on closing are ignored by the implementation of `Drop`.  Use the method
29 /// [`sync_all`] if these errors must be manually handled.
30 ///
31 /// # Examples
32 ///
33 /// Creates a new file and write bytes to it (you can also use [`write`]):
34 ///
35 /// ```no_run
36 /// use std::fs::File;
37 /// use std::io::prelude::*;
38 ///
39 /// fn main() -> std::io::Result<()> {
40 ///     let mut file = File::create("foo.txt")?;
41 ///     file.write_all(b"Hello, world!")?;
42 ///     Ok(())
43 /// }
44 /// ```
45 ///
46 /// Read the contents of a file into a [`String`] (you can also use [`read`]):
47 ///
48 /// ```no_run
49 /// use std::fs::File;
50 /// use std::io::prelude::*;
51 ///
52 /// fn main() -> std::io::Result<()> {
53 ///     let mut file = File::open("foo.txt")?;
54 ///     let mut contents = String::new();
55 ///     file.read_to_string(&mut contents)?;
56 ///     assert_eq!(contents, "Hello, world!");
57 ///     Ok(())
58 /// }
59 /// ```
60 ///
61 /// It can be more efficient to read the contents of a file with a buffered
62 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
63 ///
64 /// ```no_run
65 /// use std::fs::File;
66 /// use std::io::BufReader;
67 /// use std::io::prelude::*;
68 ///
69 /// fn main() -> std::io::Result<()> {
70 ///     let file = File::open("foo.txt")?;
71 ///     let mut buf_reader = BufReader::new(file);
72 ///     let mut contents = String::new();
73 ///     buf_reader.read_to_string(&mut contents)?;
74 ///     assert_eq!(contents, "Hello, world!");
75 ///     Ok(())
76 /// }
77 /// ```
78 ///
79 /// Note that, although read and write methods require a `&mut File`, because
80 /// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
81 /// still modify the file, either through methods that take `&File` or by
82 /// retrieving the underlying OS object and modifying the file that way.
83 /// Additionally, many operating systems allow concurrent modification of files
84 /// by different processes. Avoid assuming that holding a `&File` means that the
85 /// file will not change.
86 ///
87 /// [`Seek`]: ../io/trait.Seek.html
88 /// [`String`]: ../string/struct.String.html
89 /// [`Read`]: ../io/trait.Read.html
90 /// [`Write`]: ../io/trait.Write.html
91 /// [`BufReader<R>`]: ../io/struct.BufReader.html
92 /// [`sync_all`]: struct.File.html#method.sync_all
93 /// [`read`]: fn.read.html
94 /// [`write`]: fn.write.html
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub struct File {
97     inner: fs_imp::File,
98 }
99
100 /// Metadata information about a file.
101 ///
102 /// This structure is returned from the [`metadata`] or
103 /// [`symlink_metadata`] function or method and represents known
104 /// metadata about a file such as its permissions, size, modification
105 /// times, etc.
106 ///
107 /// [`metadata`]: fn.metadata.html
108 /// [`symlink_metadata`]: fn.symlink_metadata.html
109 #[stable(feature = "rust1", since = "1.0.0")]
110 #[derive(Clone)]
111 pub struct Metadata(fs_imp::FileAttr);
112
113 /// Iterator over the entries in a directory.
114 ///
115 /// This iterator is returned from the [`read_dir`] function of this module and
116 /// will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. Through a [`DirEntry`]
117 /// information like the entry's path and possibly other metadata can be
118 /// learned.
119 ///
120 /// The order in which this iterator returns entries is platform and filesystem
121 /// dependent.
122 ///
123 /// # Errors
124 ///
125 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
126 /// IO error during iteration.
127 ///
128 /// [`read_dir`]: fn.read_dir.html
129 /// [`DirEntry`]: struct.DirEntry.html
130 /// [`io::Result`]: ../io/type.Result.html
131 /// [`Err`]: ../result/enum.Result.html#variant.Err
132 #[stable(feature = "rust1", since = "1.0.0")]
133 #[derive(Debug)]
134 pub struct ReadDir(fs_imp::ReadDir);
135
136 /// Entries returned by the [`ReadDir`] iterator.
137 ///
138 /// [`ReadDir`]: struct.ReadDir.html
139 ///
140 /// An instance of `DirEntry` represents an entry inside of a directory on the
141 /// filesystem. Each entry can be inspected via methods to learn about the full
142 /// path or possibly other metadata through per-platform extension traits.
143 #[stable(feature = "rust1", since = "1.0.0")]
144 pub struct DirEntry(fs_imp::DirEntry);
145
146 /// Options and flags which can be used to configure how a file is opened.
147 ///
148 /// This builder exposes the ability to configure how a [`File`] is opened and
149 /// what operations are permitted on the open file. The [`File::open`] and
150 /// [`File::create`] methods are aliases for commonly used options using this
151 /// builder.
152 ///
153 /// [`File`]: struct.File.html
154 /// [`File::open`]: struct.File.html#method.open
155 /// [`File::create`]: struct.File.html#method.create
156 ///
157 /// Generally speaking, when using `OpenOptions`, you'll first call [`new`],
158 /// then chain calls to methods to set each option, then call [`open`],
159 /// passing the path of the file you're trying to open. This will give you a
160 /// [`io::Result`][result] with a [`File`][file] inside that you can further
161 /// operate on.
162 ///
163 /// [`new`]: struct.OpenOptions.html#method.new
164 /// [`open`]: struct.OpenOptions.html#method.open
165 /// [result]: ../io/type.Result.html
166 /// [file]: struct.File.html
167 ///
168 /// # Examples
169 ///
170 /// Opening a file to read:
171 ///
172 /// ```no_run
173 /// use std::fs::OpenOptions;
174 ///
175 /// let file = OpenOptions::new().read(true).open("foo.txt");
176 /// ```
177 ///
178 /// Opening a file for both reading and writing, as well as creating it if it
179 /// doesn't exist:
180 ///
181 /// ```no_run
182 /// use std::fs::OpenOptions;
183 ///
184 /// let file = OpenOptions::new()
185 ///             .read(true)
186 ///             .write(true)
187 ///             .create(true)
188 ///             .open("foo.txt");
189 /// ```
190 #[derive(Clone, Debug)]
191 #[stable(feature = "rust1", since = "1.0.0")]
192 pub struct OpenOptions(fs_imp::OpenOptions);
193
194 /// Representation of the various permissions on a file.
195 ///
196 /// This module only currently provides one bit of information, [`readonly`],
197 /// which is exposed on all currently supported platforms. Unix-specific
198 /// functionality, such as mode bits, is available through the
199 /// [`PermissionsExt`] trait.
200 ///
201 /// [`readonly`]: struct.Permissions.html#method.readonly
202 /// [`PermissionsExt`]: ../os/unix/fs/trait.PermissionsExt.html
203 #[derive(Clone, PartialEq, Eq, Debug)]
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub struct Permissions(fs_imp::FilePermissions);
206
207 /// A structure representing a type of file with accessors for each file type.
208 /// It is returned by [`Metadata::file_type`] method.
209 ///
210 /// [`Metadata::file_type`]: struct.Metadata.html#method.file_type
211 #[stable(feature = "file_type", since = "1.1.0")]
212 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
213 pub struct FileType(fs_imp::FileType);
214
215 /// A builder used to create directories in various manners.
216 ///
217 /// This builder also supports platform-specific options.
218 #[stable(feature = "dir_builder", since = "1.6.0")]
219 #[derive(Debug)]
220 pub struct DirBuilder {
221     inner: fs_imp::DirBuilder,
222     recursive: bool,
223 }
224
225 /// Indicates how large a buffer to pre-allocate before reading the entire file.
226 fn initial_buffer_size(file: &File) -> usize {
227     // Allocate one extra byte so the buffer doesn't need to grow before the
228     // final `read` call at the end of the file.  Don't worry about `usize`
229     // overflow because reading will fail regardless in that case.
230     file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
231 }
232
233 /// Read the entire contents of a file into a bytes vector.
234 ///
235 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
236 /// with fewer imports and without an intermediate variable. It pre-allocates a
237 /// buffer based on the file size when available, so it is generally faster than
238 /// reading into a vector created with `Vec::new()`.
239 ///
240 /// [`File::open`]: struct.File.html#method.open
241 /// [`read_to_end`]: ../io/trait.Read.html#method.read_to_end
242 ///
243 /// # Errors
244 ///
245 /// This function will return an error if `path` does not already exist.
246 /// Other errors may also be returned according to [`OpenOptions::open`].
247 ///
248 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
249 ///
250 /// It will also return an error if it encounters while reading an error
251 /// of a kind other than [`ErrorKind::Interrupted`].
252 ///
253 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
254 ///
255 /// # Examples
256 ///
257 /// ```no_run
258 /// use std::fs;
259 /// use std::net::SocketAddr;
260 ///
261 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
262 ///     let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
263 ///     Ok(())
264 /// }
265 /// ```
266 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
267 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
268     fn inner(path: &Path) -> io::Result<Vec<u8>> {
269         let mut file = File::open(path)?;
270         let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
271         file.read_to_end(&mut bytes)?;
272         Ok(bytes)
273     }
274     inner(path.as_ref())
275 }
276
277 /// Read the entire contents of a file into a string.
278 ///
279 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
280 /// with fewer imports and without an intermediate variable. It pre-allocates a
281 /// buffer based on the file size when available, so it is generally faster than
282 /// reading into a string created with `String::new()`.
283 ///
284 /// [`File::open`]: struct.File.html#method.open
285 /// [`read_to_string`]: ../io/trait.Read.html#method.read_to_string
286 ///
287 /// # Errors
288 ///
289 /// This function will return an error if `path` does not already exist.
290 /// Other errors may also be returned according to [`OpenOptions::open`].
291 ///
292 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
293 ///
294 /// It will also return an error if it encounters while reading an error
295 /// of a kind other than [`ErrorKind::Interrupted`],
296 /// or if the contents of the file are not valid UTF-8.
297 ///
298 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
299 ///
300 /// # Examples
301 ///
302 /// ```no_run
303 /// use std::fs;
304 /// use std::net::SocketAddr;
305 ///
306 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
307 ///     let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
308 ///     Ok(())
309 /// }
310 /// ```
311 #[stable(feature = "fs_read_write", since = "1.26.0")]
312 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
313     fn inner(path: &Path) -> io::Result<String> {
314         let mut file = File::open(path)?;
315         let mut string = String::with_capacity(initial_buffer_size(&file));
316         file.read_to_string(&mut string)?;
317         Ok(string)
318     }
319     inner(path.as_ref())
320 }
321
322 /// Write a slice as the entire contents of a file.
323 ///
324 /// This function will create a file if it does not exist,
325 /// and will entirely replace its contents if it does.
326 ///
327 /// This is a convenience function for using [`File::create`] and [`write_all`]
328 /// with fewer imports.
329 ///
330 /// [`File::create`]: struct.File.html#method.create
331 /// [`write_all`]: ../io/trait.Write.html#method.write_all
332 ///
333 /// # Examples
334 ///
335 /// ```no_run
336 /// use std::fs;
337 ///
338 /// fn main() -> std::io::Result<()> {
339 ///     fs::write("foo.txt", b"Lorem ipsum")?;
340 ///     fs::write("bar.txt", "dolor sit")?;
341 ///     Ok(())
342 /// }
343 /// ```
344 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
345 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
346     fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
347         File::create(path)?.write_all(contents)
348     }
349     inner(path.as_ref(), contents.as_ref())
350 }
351
352 impl File {
353     /// Attempts to open a file in read-only mode.
354     ///
355     /// See the [`OpenOptions::open`] method for more details.
356     ///
357     /// # Errors
358     ///
359     /// This function will return an error if `path` does not already exist.
360     /// Other errors may also be returned according to [`OpenOptions::open`].
361     ///
362     /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
363     ///
364     /// # Examples
365     ///
366     /// ```no_run
367     /// use std::fs::File;
368     ///
369     /// fn main() -> std::io::Result<()> {
370     ///     let mut f = File::open("foo.txt")?;
371     ///     Ok(())
372     /// }
373     /// ```
374     #[stable(feature = "rust1", since = "1.0.0")]
375     pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
376         OpenOptions::new().read(true).open(path.as_ref())
377     }
378
379     /// Opens a file in write-only mode.
380     ///
381     /// This function will create a file if it does not exist,
382     /// and will truncate it if it does.
383     ///
384     /// See the [`OpenOptions::open`] function for more details.
385     ///
386     /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
387     ///
388     /// # Examples
389     ///
390     /// ```no_run
391     /// use std::fs::File;
392     ///
393     /// fn main() -> std::io::Result<()> {
394     ///     let mut f = File::create("foo.txt")?;
395     ///     Ok(())
396     /// }
397     /// ```
398     #[stable(feature = "rust1", since = "1.0.0")]
399     pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
400         OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
401     }
402
403     /// Returns a new OpenOptions object.
404     ///
405     /// This function returns a new OpenOptions object that you can use to
406     /// open or create a file with specific options if `open()` or `create()`
407     /// are not appropriate.
408     ///
409     /// It is equivalent to `OpenOptions::new()` but allows you to write more
410     /// readable code. Instead of `OpenOptions::new().read(true).open("foo.txt")`
411     /// you can write `File::with_options().read(true).open("foo.txt")`. This
412     /// also avoids the need to import `OpenOptions`.
413     ///
414     /// See the [`OpenOptions::new`] function for more details.
415     ///
416     /// [`OpenOptions::new`]: struct.OpenOptions.html#method.new
417     ///
418     /// # Examples
419     ///
420     /// ```no_run
421     /// #![feature(with_options)]
422     /// use std::fs::File;
423     ///
424     /// fn main() -> std::io::Result<()> {
425     ///     let mut f = File::with_options().read(true).open("foo.txt")?;
426     ///     Ok(())
427     /// }
428     /// ```
429     #[unstable(feature = "with_options", issue = "65439")]
430     pub fn with_options() -> OpenOptions {
431         OpenOptions::new()
432     }
433
434     /// Attempts to sync all OS-internal metadata to disk.
435     ///
436     /// This function will attempt to ensure that all in-memory data reaches the
437     /// filesystem before returning.
438     ///
439     /// This can be used to handle errors that would otherwise only be caught
440     /// when the `File` is closed.  Dropping a file will ignore errors in
441     /// synchronizing this in-memory data.
442     ///
443     /// # Examples
444     ///
445     /// ```no_run
446     /// use std::fs::File;
447     /// use std::io::prelude::*;
448     ///
449     /// fn main() -> std::io::Result<()> {
450     ///     let mut f = File::create("foo.txt")?;
451     ///     f.write_all(b"Hello, world!")?;
452     ///
453     ///     f.sync_all()?;
454     ///     Ok(())
455     /// }
456     /// ```
457     #[stable(feature = "rust1", since = "1.0.0")]
458     pub fn sync_all(&self) -> io::Result<()> {
459         self.inner.fsync()
460     }
461
462     /// This function is similar to [`sync_all`], except that it may not
463     /// synchronize file metadata to the filesystem.
464     ///
465     /// This is intended for use cases that must synchronize content, but don't
466     /// need the metadata on disk. The goal of this method is to reduce disk
467     /// operations.
468     ///
469     /// Note that some platforms may simply implement this in terms of
470     /// [`sync_all`].
471     ///
472     /// [`sync_all`]: struct.File.html#method.sync_all
473     ///
474     /// # Examples
475     ///
476     /// ```no_run
477     /// use std::fs::File;
478     /// use std::io::prelude::*;
479     ///
480     /// fn main() -> std::io::Result<()> {
481     ///     let mut f = File::create("foo.txt")?;
482     ///     f.write_all(b"Hello, world!")?;
483     ///
484     ///     f.sync_data()?;
485     ///     Ok(())
486     /// }
487     /// ```
488     #[stable(feature = "rust1", since = "1.0.0")]
489     pub fn sync_data(&self) -> io::Result<()> {
490         self.inner.datasync()
491     }
492
493     /// Truncates or extends the underlying file, updating the size of
494     /// this file to become `size`.
495     ///
496     /// If the `size` is less than the current file's size, then the file will
497     /// be shrunk. If it is greater than the current file's size, then the file
498     /// will be extended to `size` and have all of the intermediate data filled
499     /// in with 0s.
500     ///
501     /// The file's cursor isn't changed. In particular, if the cursor was at the
502     /// end and the file is shrunk using this operation, the cursor will now be
503     /// past the end.
504     ///
505     /// # Errors
506     ///
507     /// This function will return an error if the file is not opened for writing.
508     /// Also, std::io::ErrorKind::InvalidInput will be returned if the desired
509     /// length would cause an overflow due to the implementation specifics.
510     ///
511     /// # Examples
512     ///
513     /// ```no_run
514     /// use std::fs::File;
515     ///
516     /// fn main() -> std::io::Result<()> {
517     ///     let mut f = File::create("foo.txt")?;
518     ///     f.set_len(10)?;
519     ///     Ok(())
520     /// }
521     /// ```
522     ///
523     /// Note that this method alters the content of the underlying file, even
524     /// though it takes `&self` rather than `&mut self`.
525     #[stable(feature = "rust1", since = "1.0.0")]
526     pub fn set_len(&self, size: u64) -> io::Result<()> {
527         self.inner.truncate(size)
528     }
529
530     /// Queries metadata about the underlying file.
531     ///
532     /// # Examples
533     ///
534     /// ```no_run
535     /// use std::fs::File;
536     ///
537     /// fn main() -> std::io::Result<()> {
538     ///     let mut f = File::open("foo.txt")?;
539     ///     let metadata = f.metadata()?;
540     ///     Ok(())
541     /// }
542     /// ```
543     #[stable(feature = "rust1", since = "1.0.0")]
544     pub fn metadata(&self) -> io::Result<Metadata> {
545         self.inner.file_attr().map(Metadata)
546     }
547
548     /// Creates a new `File` instance that shares the same underlying file handle
549     /// as the existing `File` instance. Reads, writes, and seeks will affect
550     /// both `File` instances simultaneously.
551     ///
552     /// # Examples
553     ///
554     /// Creates two handles for a file named `foo.txt`:
555     ///
556     /// ```no_run
557     /// use std::fs::File;
558     ///
559     /// fn main() -> std::io::Result<()> {
560     ///     let mut file = File::open("foo.txt")?;
561     ///     let file_copy = file.try_clone()?;
562     ///     Ok(())
563     /// }
564     /// ```
565     ///
566     /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
567     /// two handles, seek one of them, and read the remaining bytes from the
568     /// other handle:
569     ///
570     /// ```no_run
571     /// use std::fs::File;
572     /// use std::io::SeekFrom;
573     /// use std::io::prelude::*;
574     ///
575     /// fn main() -> std::io::Result<()> {
576     ///     let mut file = File::open("foo.txt")?;
577     ///     let mut file_copy = file.try_clone()?;
578     ///
579     ///     file.seek(SeekFrom::Start(3))?;
580     ///
581     ///     let mut contents = vec![];
582     ///     file_copy.read_to_end(&mut contents)?;
583     ///     assert_eq!(contents, b"def\n");
584     ///     Ok(())
585     /// }
586     /// ```
587     #[stable(feature = "file_try_clone", since = "1.9.0")]
588     pub fn try_clone(&self) -> io::Result<File> {
589         Ok(File { inner: self.inner.duplicate()? })
590     }
591
592     /// Changes the permissions on the underlying file.
593     ///
594     /// # Platform-specific behavior
595     ///
596     /// This function currently corresponds to the `fchmod` function on Unix and
597     /// the `SetFileInformationByHandle` function on Windows. Note that, this
598     /// [may change in the future][changes].
599     ///
600     /// [changes]: ../io/index.html#platform-specific-behavior
601     ///
602     /// # Errors
603     ///
604     /// This function will return an error if the user lacks permission change
605     /// attributes on the underlying file. It may also return an error in other
606     /// os-specific unspecified cases.
607     ///
608     /// # Examples
609     ///
610     /// ```no_run
611     /// fn main() -> std::io::Result<()> {
612     ///     use std::fs::File;
613     ///
614     ///     let file = File::open("foo.txt")?;
615     ///     let mut perms = file.metadata()?.permissions();
616     ///     perms.set_readonly(true);
617     ///     file.set_permissions(perms)?;
618     ///     Ok(())
619     /// }
620     /// ```
621     ///
622     /// Note that this method alters the permissions of the underlying file,
623     /// even though it takes `&self` rather than `&mut self`.
624     #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
625     pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
626         self.inner.set_permissions(perm.0)
627     }
628 }
629
630 impl AsInner<fs_imp::File> for File {
631     fn as_inner(&self) -> &fs_imp::File {
632         &self.inner
633     }
634 }
635 impl FromInner<fs_imp::File> for File {
636     fn from_inner(f: fs_imp::File) -> File {
637         File { inner: f }
638     }
639 }
640 impl IntoInner<fs_imp::File> for File {
641     fn into_inner(self) -> fs_imp::File {
642         self.inner
643     }
644 }
645
646 #[stable(feature = "rust1", since = "1.0.0")]
647 impl fmt::Debug for File {
648     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
649         self.inner.fmt(f)
650     }
651 }
652
653 #[stable(feature = "rust1", since = "1.0.0")]
654 impl Read for File {
655     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
656         self.inner.read(buf)
657     }
658
659     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
660         self.inner.read_vectored(bufs)
661     }
662
663     #[inline]
664     fn is_read_vectored(&self) -> bool {
665         self.inner.is_read_vectored()
666     }
667
668     #[inline]
669     unsafe fn initializer(&self) -> Initializer {
670         // SAFETY: Read is guaranteed to work on uninitialized memory
671         unsafe { Initializer::nop() }
672     }
673 }
674 #[stable(feature = "rust1", since = "1.0.0")]
675 impl Write for File {
676     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
677         self.inner.write(buf)
678     }
679
680     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
681         self.inner.write_vectored(bufs)
682     }
683
684     #[inline]
685     fn is_write_vectored(&self) -> bool {
686         self.inner.is_write_vectored()
687     }
688
689     fn flush(&mut self) -> io::Result<()> {
690         self.inner.flush()
691     }
692 }
693 #[stable(feature = "rust1", since = "1.0.0")]
694 impl Seek for File {
695     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
696         self.inner.seek(pos)
697     }
698 }
699 #[stable(feature = "rust1", since = "1.0.0")]
700 impl Read for &File {
701     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
702         self.inner.read(buf)
703     }
704
705     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
706         self.inner.read_vectored(bufs)
707     }
708
709     #[inline]
710     fn is_read_vectored(&self) -> bool {
711         self.inner.is_read_vectored()
712     }
713
714     #[inline]
715     unsafe fn initializer(&self) -> Initializer {
716         // SAFETY: Read is guaranteed to work on uninitialized memory
717         unsafe { Initializer::nop() }
718     }
719 }
720 #[stable(feature = "rust1", since = "1.0.0")]
721 impl Write for &File {
722     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
723         self.inner.write(buf)
724     }
725
726     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
727         self.inner.write_vectored(bufs)
728     }
729
730     #[inline]
731     fn is_write_vectored(&self) -> bool {
732         self.inner.is_write_vectored()
733     }
734
735     fn flush(&mut self) -> io::Result<()> {
736         self.inner.flush()
737     }
738 }
739 #[stable(feature = "rust1", since = "1.0.0")]
740 impl Seek for &File {
741     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
742         self.inner.seek(pos)
743     }
744 }
745
746 impl OpenOptions {
747     /// Creates a blank new set of options ready for configuration.
748     ///
749     /// All options are initially set to `false`.
750     ///
751     /// # Examples
752     ///
753     /// ```no_run
754     /// use std::fs::OpenOptions;
755     ///
756     /// let mut options = OpenOptions::new();
757     /// let file = options.read(true).open("foo.txt");
758     /// ```
759     #[stable(feature = "rust1", since = "1.0.0")]
760     pub fn new() -> Self {
761         OpenOptions(fs_imp::OpenOptions::new())
762     }
763
764     /// Sets the option for read access.
765     ///
766     /// This option, when true, will indicate that the file should be
767     /// `read`-able if opened.
768     ///
769     /// # Examples
770     ///
771     /// ```no_run
772     /// use std::fs::OpenOptions;
773     ///
774     /// let file = OpenOptions::new().read(true).open("foo.txt");
775     /// ```
776     #[stable(feature = "rust1", since = "1.0.0")]
777     pub fn read(&mut self, read: bool) -> &mut Self {
778         self.0.read(read);
779         self
780     }
781
782     /// Sets the option for write access.
783     ///
784     /// This option, when true, will indicate that the file should be
785     /// `write`-able if opened.
786     ///
787     /// If the file already exists, any write calls on it will overwrite its
788     /// contents, without truncating it.
789     ///
790     /// # Examples
791     ///
792     /// ```no_run
793     /// use std::fs::OpenOptions;
794     ///
795     /// let file = OpenOptions::new().write(true).open("foo.txt");
796     /// ```
797     #[stable(feature = "rust1", since = "1.0.0")]
798     pub fn write(&mut self, write: bool) -> &mut Self {
799         self.0.write(write);
800         self
801     }
802
803     /// Sets the option for the append mode.
804     ///
805     /// This option, when true, means that writes will append to a file instead
806     /// of overwriting previous contents.
807     /// Note that setting `.write(true).append(true)` has the same effect as
808     /// setting only `.append(true)`.
809     ///
810     /// For most filesystems, the operating system guarantees that all writes are
811     /// atomic: no writes get mangled because another process writes at the same
812     /// time.
813     ///
814     /// One maybe obvious note when using append-mode: make sure that all data
815     /// that belongs together is written to the file in one operation. This
816     /// can be done by concatenating strings before passing them to [`write()`],
817     /// or using a buffered writer (with a buffer of adequate size),
818     /// and calling [`flush()`] when the message is complete.
819     ///
820     /// If a file is opened with both read and append access, beware that after
821     /// opening, and after every write, the position for reading may be set at the
822     /// end of the file. So, before writing, save the current position (using
823     /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`), and restore it before the next read.
824     ///
825     /// ## Note
826     ///
827     /// This function doesn't create the file if it doesn't exist. Use the [`create`]
828     /// method to do so.
829     ///
830     /// [`write()`]: ../../std/fs/struct.File.html#method.write
831     /// [`flush()`]: ../../std/fs/struct.File.html#method.flush
832     /// [`seek`]: ../../std/fs/struct.File.html#method.seek
833     /// [`SeekFrom`]: ../../std/io/enum.SeekFrom.html
834     /// [`Current`]: ../../std/io/enum.SeekFrom.html#variant.Current
835     /// [`create`]: #method.create
836     ///
837     /// # Examples
838     ///
839     /// ```no_run
840     /// use std::fs::OpenOptions;
841     ///
842     /// let file = OpenOptions::new().append(true).open("foo.txt");
843     /// ```
844     #[stable(feature = "rust1", since = "1.0.0")]
845     pub fn append(&mut self, append: bool) -> &mut Self {
846         self.0.append(append);
847         self
848     }
849
850     /// Sets the option for truncating a previous file.
851     ///
852     /// If a file is successfully opened with this option set it will truncate
853     /// the file to 0 length if it already exists.
854     ///
855     /// The file must be opened with write access for truncate to work.
856     ///
857     /// # Examples
858     ///
859     /// ```no_run
860     /// use std::fs::OpenOptions;
861     ///
862     /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
863     /// ```
864     #[stable(feature = "rust1", since = "1.0.0")]
865     pub fn truncate(&mut self, truncate: bool) -> &mut Self {
866         self.0.truncate(truncate);
867         self
868     }
869
870     /// Sets the option to create a new file, or open it if it already exists.
871     ///
872     /// In order for the file to be created, [`write`] or [`append`] access must
873     /// be used.
874     ///
875     /// [`write`]: #method.write
876     /// [`append`]: #method.append
877     ///
878     /// # Examples
879     ///
880     /// ```no_run
881     /// use std::fs::OpenOptions;
882     ///
883     /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
884     /// ```
885     #[stable(feature = "rust1", since = "1.0.0")]
886     pub fn create(&mut self, create: bool) -> &mut Self {
887         self.0.create(create);
888         self
889     }
890
891     /// Sets the option to create a new file, failing if it already exists.
892     ///
893     /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
894     /// way, if the call succeeds, the file returned is guaranteed to be new.
895     ///
896     /// This option is useful because it is atomic. Otherwise between checking
897     /// whether a file exists and creating a new one, the file may have been
898     /// created by another process (a TOCTOU race condition / attack).
899     ///
900     /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
901     /// ignored.
902     ///
903     /// The file must be opened with write or append access in order to create
904     /// a new file.
905     ///
906     /// [`.create()`]: #method.create
907     /// [`.truncate()`]: #method.truncate
908     ///
909     /// # Examples
910     ///
911     /// ```no_run
912     /// use std::fs::OpenOptions;
913     ///
914     /// let file = OpenOptions::new().write(true)
915     ///                              .create_new(true)
916     ///                              .open("foo.txt");
917     /// ```
918     #[stable(feature = "expand_open_options2", since = "1.9.0")]
919     pub fn create_new(&mut self, create_new: bool) -> &mut Self {
920         self.0.create_new(create_new);
921         self
922     }
923
924     /// Opens a file at `path` with the options specified by `self`.
925     ///
926     /// # Errors
927     ///
928     /// This function will return an error under a number of different
929     /// circumstances. Some of these error conditions are listed here, together
930     /// with their [`ErrorKind`]. The mapping to [`ErrorKind`]s is not part of
931     /// the compatibility contract of the function, especially the `Other` kind
932     /// might change to more specific kinds in the future.
933     ///
934     /// * [`NotFound`]: The specified file does not exist and neither `create`
935     ///   or `create_new` is set.
936     /// * [`NotFound`]: One of the directory components of the file path does
937     ///   not exist.
938     /// * [`PermissionDenied`]: The user lacks permission to get the specified
939     ///   access rights for the file.
940     /// * [`PermissionDenied`]: The user lacks permission to open one of the
941     ///   directory components of the specified path.
942     /// * [`AlreadyExists`]: `create_new` was specified and the file already
943     ///   exists.
944     /// * [`InvalidInput`]: Invalid combinations of open options (truncate
945     ///   without write access, no access mode set, etc.).
946     /// * [`Other`]: One of the directory components of the specified file path
947     ///   was not, in fact, a directory.
948     /// * [`Other`]: Filesystem-level errors: full disk, write permission
949     ///   requested on a read-only file system, exceeded disk quota, too many
950     ///   open files, too long filename, too many symbolic links in the
951     ///   specified path (Unix-like systems only), etc.
952     ///
953     /// # Examples
954     ///
955     /// ```no_run
956     /// use std::fs::OpenOptions;
957     ///
958     /// let file = OpenOptions::new().read(true).open("foo.txt");
959     /// ```
960     ///
961     /// [`ErrorKind`]: ../io/enum.ErrorKind.html
962     /// [`AlreadyExists`]: ../io/enum.ErrorKind.html#variant.AlreadyExists
963     /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
964     /// [`NotFound`]: ../io/enum.ErrorKind.html#variant.NotFound
965     /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
966     /// [`PermissionDenied`]: ../io/enum.ErrorKind.html#variant.PermissionDenied
967     #[stable(feature = "rust1", since = "1.0.0")]
968     pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
969         self._open(path.as_ref())
970     }
971
972     fn _open(&self, path: &Path) -> io::Result<File> {
973         fs_imp::File::open(path, &self.0).map(|inner| File { inner })
974     }
975 }
976
977 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
978     fn as_inner(&self) -> &fs_imp::OpenOptions {
979         &self.0
980     }
981 }
982
983 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
984     fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
985         &mut self.0
986     }
987 }
988
989 impl Metadata {
990     /// Returns the file type for this metadata.
991     ///
992     /// # Examples
993     ///
994     /// ```no_run
995     /// fn main() -> std::io::Result<()> {
996     ///     use std::fs;
997     ///
998     ///     let metadata = fs::metadata("foo.txt")?;
999     ///
1000     ///     println!("{:?}", metadata.file_type());
1001     ///     Ok(())
1002     /// }
1003     /// ```
1004     #[stable(feature = "file_type", since = "1.1.0")]
1005     pub fn file_type(&self) -> FileType {
1006         FileType(self.0.file_type())
1007     }
1008
1009     /// Returns `true` if this metadata is for a directory. The
1010     /// result is mutually exclusive to the result of
1011     /// [`is_file`], and will be false for symlink metadata
1012     /// obtained from [`symlink_metadata`].
1013     ///
1014     /// [`is_file`]: struct.Metadata.html#method.is_file
1015     /// [`symlink_metadata`]: fn.symlink_metadata.html
1016     ///
1017     /// # Examples
1018     ///
1019     /// ```no_run
1020     /// fn main() -> std::io::Result<()> {
1021     ///     use std::fs;
1022     ///
1023     ///     let metadata = fs::metadata("foo.txt")?;
1024     ///
1025     ///     assert!(!metadata.is_dir());
1026     ///     Ok(())
1027     /// }
1028     /// ```
1029     #[stable(feature = "rust1", since = "1.0.0")]
1030     pub fn is_dir(&self) -> bool {
1031         self.file_type().is_dir()
1032     }
1033
1034     /// Returns `true` if this metadata is for a regular file. The
1035     /// result is mutually exclusive to the result of
1036     /// [`is_dir`], and will be false for symlink metadata
1037     /// obtained from [`symlink_metadata`].
1038     ///
1039     /// When the goal is simply to read from (or write to) the source, the most
1040     /// reliable way to test the source can be read (or written to) is to open
1041     /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1042     /// a Unix-like system for example. See [`File::open`] or
1043     /// [`OpenOptions::open`] for more information.
1044     ///
1045     /// [`is_dir`]: struct.Metadata.html#method.is_dir
1046     /// [`symlink_metadata`]: fn.symlink_metadata.html
1047     /// [`File::open`]: struct.File.html#method.open
1048     /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
1049     ///
1050     /// # Examples
1051     ///
1052     /// ```no_run
1053     /// use std::fs;
1054     ///
1055     /// fn main() -> std::io::Result<()> {
1056     ///     let metadata = fs::metadata("foo.txt")?;
1057     ///
1058     ///     assert!(metadata.is_file());
1059     ///     Ok(())
1060     /// }
1061     /// ```
1062     #[stable(feature = "rust1", since = "1.0.0")]
1063     pub fn is_file(&self) -> bool {
1064         self.file_type().is_file()
1065     }
1066
1067     /// Returns the size of the file, in bytes, this metadata is for.
1068     ///
1069     /// # Examples
1070     ///
1071     /// ```no_run
1072     /// use std::fs;
1073     ///
1074     /// fn main() -> std::io::Result<()> {
1075     ///     let metadata = fs::metadata("foo.txt")?;
1076     ///
1077     ///     assert_eq!(0, metadata.len());
1078     ///     Ok(())
1079     /// }
1080     /// ```
1081     #[stable(feature = "rust1", since = "1.0.0")]
1082     pub fn len(&self) -> u64 {
1083         self.0.size()
1084     }
1085
1086     /// Returns the permissions of the file this metadata is for.
1087     ///
1088     /// # Examples
1089     ///
1090     /// ```no_run
1091     /// use std::fs;
1092     ///
1093     /// fn main() -> std::io::Result<()> {
1094     ///     let metadata = fs::metadata("foo.txt")?;
1095     ///
1096     ///     assert!(!metadata.permissions().readonly());
1097     ///     Ok(())
1098     /// }
1099     /// ```
1100     #[stable(feature = "rust1", since = "1.0.0")]
1101     pub fn permissions(&self) -> Permissions {
1102         Permissions(self.0.perm())
1103     }
1104
1105     /// Returns the last modification time listed in this metadata.
1106     ///
1107     /// The returned value corresponds to the `mtime` field of `stat` on Unix
1108     /// platforms and the `ftLastWriteTime` field on Windows platforms.
1109     ///
1110     /// # Errors
1111     ///
1112     /// This field may not be available on all platforms, and will return an
1113     /// `Err` on platforms where it is not available.
1114     ///
1115     /// # Examples
1116     ///
1117     /// ```no_run
1118     /// use std::fs;
1119     ///
1120     /// fn main() -> std::io::Result<()> {
1121     ///     let metadata = fs::metadata("foo.txt")?;
1122     ///
1123     ///     if let Ok(time) = metadata.modified() {
1124     ///         println!("{:?}", time);
1125     ///     } else {
1126     ///         println!("Not supported on this platform");
1127     ///     }
1128     ///     Ok(())
1129     /// }
1130     /// ```
1131     #[stable(feature = "fs_time", since = "1.10.0")]
1132     pub fn modified(&self) -> io::Result<SystemTime> {
1133         self.0.modified().map(FromInner::from_inner)
1134     }
1135
1136     /// Returns the last access time of this metadata.
1137     ///
1138     /// The returned value corresponds to the `atime` field of `stat` on Unix
1139     /// platforms and the `ftLastAccessTime` field on Windows platforms.
1140     ///
1141     /// Note that not all platforms will keep this field update in a file's
1142     /// metadata, for example Windows has an option to disable updating this
1143     /// time when files are accessed and Linux similarly has `noatime`.
1144     ///
1145     /// # Errors
1146     ///
1147     /// This field may not be available on all platforms, and will return an
1148     /// `Err` on platforms where it is not available.
1149     ///
1150     /// # Examples
1151     ///
1152     /// ```no_run
1153     /// use std::fs;
1154     ///
1155     /// fn main() -> std::io::Result<()> {
1156     ///     let metadata = fs::metadata("foo.txt")?;
1157     ///
1158     ///     if let Ok(time) = metadata.accessed() {
1159     ///         println!("{:?}", time);
1160     ///     } else {
1161     ///         println!("Not supported on this platform");
1162     ///     }
1163     ///     Ok(())
1164     /// }
1165     /// ```
1166     #[stable(feature = "fs_time", since = "1.10.0")]
1167     pub fn accessed(&self) -> io::Result<SystemTime> {
1168         self.0.accessed().map(FromInner::from_inner)
1169     }
1170
1171     /// Returns the creation time listed in this metadata.
1172     ///
1173     /// The returned value corresponds to the `btime` field of `statx` on
1174     /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1175     /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1176     ///
1177     /// # Errors
1178     ///
1179     /// This field may not be available on all platforms, and will return an
1180     /// `Err` on platforms or filesystems where it is not available.
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     ///     if let Ok(time) = metadata.created() {
1191     ///         println!("{:?}", time);
1192     ///     } else {
1193     ///         println!("Not supported on this platform or filesystem");
1194     ///     }
1195     ///     Ok(())
1196     /// }
1197     /// ```
1198     #[stable(feature = "fs_time", since = "1.10.0")]
1199     pub fn created(&self) -> io::Result<SystemTime> {
1200         self.0.created().map(FromInner::from_inner)
1201     }
1202 }
1203
1204 #[stable(feature = "std_debug", since = "1.16.0")]
1205 impl fmt::Debug for Metadata {
1206     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1207         f.debug_struct("Metadata")
1208             .field("file_type", &self.file_type())
1209             .field("is_dir", &self.is_dir())
1210             .field("is_file", &self.is_file())
1211             .field("permissions", &self.permissions())
1212             .field("modified", &self.modified())
1213             .field("accessed", &self.accessed())
1214             .field("created", &self.created())
1215             .finish()
1216     }
1217 }
1218
1219 impl AsInner<fs_imp::FileAttr> for Metadata {
1220     fn as_inner(&self) -> &fs_imp::FileAttr {
1221         &self.0
1222     }
1223 }
1224
1225 impl FromInner<fs_imp::FileAttr> for Metadata {
1226     fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1227         Metadata(attr)
1228     }
1229 }
1230
1231 impl Permissions {
1232     /// Returns `true` if these permissions describe a readonly (unwritable) file.
1233     ///
1234     /// # Examples
1235     ///
1236     /// ```no_run
1237     /// use std::fs::File;
1238     ///
1239     /// fn main() -> std::io::Result<()> {
1240     ///     let mut f = File::create("foo.txt")?;
1241     ///     let metadata = f.metadata()?;
1242     ///
1243     ///     assert_eq!(false, metadata.permissions().readonly());
1244     ///     Ok(())
1245     /// }
1246     /// ```
1247     #[stable(feature = "rust1", since = "1.0.0")]
1248     pub fn readonly(&self) -> bool {
1249         self.0.readonly()
1250     }
1251
1252     /// Modifies the readonly flag for this set of permissions. If the
1253     /// `readonly` argument is `true`, using the resulting `Permission` will
1254     /// update file permissions to forbid writing. Conversely, if it's `false`,
1255     /// using the resulting `Permission` will update file permissions to allow
1256     /// writing.
1257     ///
1258     /// This operation does **not** modify the filesystem. To modify the
1259     /// filesystem use the [`fs::set_permissions`] function.
1260     ///
1261     /// [`fs::set_permissions`]: fn.set_permissions.html
1262     ///
1263     /// # Examples
1264     ///
1265     /// ```no_run
1266     /// use std::fs::File;
1267     ///
1268     /// fn main() -> std::io::Result<()> {
1269     ///     let f = File::create("foo.txt")?;
1270     ///     let metadata = f.metadata()?;
1271     ///     let mut permissions = metadata.permissions();
1272     ///
1273     ///     permissions.set_readonly(true);
1274     ///
1275     ///     // filesystem doesn't change
1276     ///     assert_eq!(false, metadata.permissions().readonly());
1277     ///
1278     ///     // just this particular `permissions`.
1279     ///     assert_eq!(true, permissions.readonly());
1280     ///     Ok(())
1281     /// }
1282     /// ```
1283     #[stable(feature = "rust1", since = "1.0.0")]
1284     pub fn set_readonly(&mut self, readonly: bool) {
1285         self.0.set_readonly(readonly)
1286     }
1287 }
1288
1289 impl FileType {
1290     /// Tests whether this file type represents a directory. The
1291     /// result is mutually exclusive to the results of
1292     /// [`is_file`] and [`is_symlink`]; only zero or one of these
1293     /// tests may pass.
1294     ///
1295     /// [`is_file`]: struct.FileType.html#method.is_file
1296     /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1297     ///
1298     /// # Examples
1299     ///
1300     /// ```no_run
1301     /// fn main() -> std::io::Result<()> {
1302     ///     use std::fs;
1303     ///
1304     ///     let metadata = fs::metadata("foo.txt")?;
1305     ///     let file_type = metadata.file_type();
1306     ///
1307     ///     assert_eq!(file_type.is_dir(), false);
1308     ///     Ok(())
1309     /// }
1310     /// ```
1311     #[stable(feature = "file_type", since = "1.1.0")]
1312     pub fn is_dir(&self) -> bool {
1313         self.0.is_dir()
1314     }
1315
1316     /// Tests whether this file type represents a regular file.
1317     /// The result is  mutually exclusive to the results of
1318     /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1319     /// tests may pass.
1320     ///
1321     /// When the goal is simply to read from (or write to) the source, the most
1322     /// reliable way to test the source can be read (or written to) is to open
1323     /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1324     /// a Unix-like system for example. See [`File::open`] or
1325     /// [`OpenOptions::open`] for more information.
1326     ///
1327     /// [`is_dir`]: struct.FileType.html#method.is_dir
1328     /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1329     /// [`File::open`]: struct.File.html#method.open
1330     /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
1331     ///
1332     /// # Examples
1333     ///
1334     /// ```no_run
1335     /// fn main() -> std::io::Result<()> {
1336     ///     use std::fs;
1337     ///
1338     ///     let metadata = fs::metadata("foo.txt")?;
1339     ///     let file_type = metadata.file_type();
1340     ///
1341     ///     assert_eq!(file_type.is_file(), true);
1342     ///     Ok(())
1343     /// }
1344     /// ```
1345     #[stable(feature = "file_type", since = "1.1.0")]
1346     pub fn is_file(&self) -> bool {
1347         self.0.is_file()
1348     }
1349
1350     /// Tests whether this file type represents a symbolic link.
1351     /// The result is mutually exclusive to the results of
1352     /// [`is_dir`] and [`is_file`]; only zero or one of these
1353     /// tests may pass.
1354     ///
1355     /// The underlying [`Metadata`] struct needs to be retrieved
1356     /// with the [`fs::symlink_metadata`] function and not the
1357     /// [`fs::metadata`] function. The [`fs::metadata`] function
1358     /// follows symbolic links, so [`is_symlink`] would always
1359     /// return `false` for the target file.
1360     ///
1361     /// [`Metadata`]: struct.Metadata.html
1362     /// [`fs::metadata`]: fn.metadata.html
1363     /// [`fs::symlink_metadata`]: fn.symlink_metadata.html
1364     /// [`is_dir`]: struct.FileType.html#method.is_dir
1365     /// [`is_file`]: struct.FileType.html#method.is_file
1366     /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1367     ///
1368     /// # Examples
1369     ///
1370     /// ```no_run
1371     /// use std::fs;
1372     ///
1373     /// fn main() -> std::io::Result<()> {
1374     ///     let metadata = fs::symlink_metadata("foo.txt")?;
1375     ///     let file_type = metadata.file_type();
1376     ///
1377     ///     assert_eq!(file_type.is_symlink(), false);
1378     ///     Ok(())
1379     /// }
1380     /// ```
1381     #[stable(feature = "file_type", since = "1.1.0")]
1382     pub fn is_symlink(&self) -> bool {
1383         self.0.is_symlink()
1384     }
1385 }
1386
1387 impl AsInner<fs_imp::FileType> for FileType {
1388     fn as_inner(&self) -> &fs_imp::FileType {
1389         &self.0
1390     }
1391 }
1392
1393 impl FromInner<fs_imp::FilePermissions> for Permissions {
1394     fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1395         Permissions(f)
1396     }
1397 }
1398
1399 impl AsInner<fs_imp::FilePermissions> for Permissions {
1400     fn as_inner(&self) -> &fs_imp::FilePermissions {
1401         &self.0
1402     }
1403 }
1404
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 impl Iterator for ReadDir {
1407     type Item = io::Result<DirEntry>;
1408
1409     fn next(&mut self) -> Option<io::Result<DirEntry>> {
1410         self.0.next().map(|entry| entry.map(DirEntry))
1411     }
1412 }
1413
1414 impl DirEntry {
1415     /// Returns the full path to the file that this entry represents.
1416     ///
1417     /// The full path is created by joining the original path to `read_dir`
1418     /// with the filename of this entry.
1419     ///
1420     /// # Examples
1421     ///
1422     /// ```no_run
1423     /// use std::fs;
1424     ///
1425     /// fn main() -> std::io::Result<()> {
1426     ///     for entry in fs::read_dir(".")? {
1427     ///         let dir = entry?;
1428     ///         println!("{:?}", dir.path());
1429     ///     }
1430     ///     Ok(())
1431     /// }
1432     /// ```
1433     ///
1434     /// This prints output like:
1435     ///
1436     /// ```text
1437     /// "./whatever.txt"
1438     /// "./foo.html"
1439     /// "./hello_world.rs"
1440     /// ```
1441     ///
1442     /// The exact text, of course, depends on what files you have in `.`.
1443     #[stable(feature = "rust1", since = "1.0.0")]
1444     pub fn path(&self) -> PathBuf {
1445         self.0.path()
1446     }
1447
1448     /// Returns the metadata for the file that this entry points at.
1449     ///
1450     /// This function will not traverse symlinks if this entry points at a
1451     /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1452     ///
1453     /// [`fs::metadata`]: fn.metadata.html
1454     /// [`fs::File::metadata`]: struct.File.html#method.metadata
1455     ///
1456     /// # Platform-specific behavior
1457     ///
1458     /// On Windows this function is cheap to call (no extra system calls
1459     /// needed), but on Unix platforms this function is the equivalent of
1460     /// calling `symlink_metadata` on the path.
1461     ///
1462     /// # Examples
1463     ///
1464     /// ```
1465     /// use std::fs;
1466     ///
1467     /// if let Ok(entries) = fs::read_dir(".") {
1468     ///     for entry in entries {
1469     ///         if let Ok(entry) = entry {
1470     ///             // Here, `entry` is a `DirEntry`.
1471     ///             if let Ok(metadata) = entry.metadata() {
1472     ///                 // Now let's show our entry's permissions!
1473     ///                 println!("{:?}: {:?}", entry.path(), metadata.permissions());
1474     ///             } else {
1475     ///                 println!("Couldn't get metadata for {:?}", entry.path());
1476     ///             }
1477     ///         }
1478     ///     }
1479     /// }
1480     /// ```
1481     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1482     pub fn metadata(&self) -> io::Result<Metadata> {
1483         self.0.metadata().map(Metadata)
1484     }
1485
1486     /// Returns the file type for the file that this entry points at.
1487     ///
1488     /// This function will not traverse symlinks if this entry points at a
1489     /// symlink.
1490     ///
1491     /// # Platform-specific behavior
1492     ///
1493     /// On Windows and most Unix platforms this function is free (no extra
1494     /// system calls needed), but some Unix platforms may require the equivalent
1495     /// call to `symlink_metadata` to learn about the target file type.
1496     ///
1497     /// # Examples
1498     ///
1499     /// ```
1500     /// use std::fs;
1501     ///
1502     /// if let Ok(entries) = fs::read_dir(".") {
1503     ///     for entry in entries {
1504     ///         if let Ok(entry) = entry {
1505     ///             // Here, `entry` is a `DirEntry`.
1506     ///             if let Ok(file_type) = entry.file_type() {
1507     ///                 // Now let's show our entry's file type!
1508     ///                 println!("{:?}: {:?}", entry.path(), file_type);
1509     ///             } else {
1510     ///                 println!("Couldn't get file type for {:?}", entry.path());
1511     ///             }
1512     ///         }
1513     ///     }
1514     /// }
1515     /// ```
1516     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1517     pub fn file_type(&self) -> io::Result<FileType> {
1518         self.0.file_type().map(FileType)
1519     }
1520
1521     /// Returns the bare file name of this directory entry without any other
1522     /// leading path component.
1523     ///
1524     /// # Examples
1525     ///
1526     /// ```
1527     /// use std::fs;
1528     ///
1529     /// if let Ok(entries) = fs::read_dir(".") {
1530     ///     for entry in entries {
1531     ///         if let Ok(entry) = entry {
1532     ///             // Here, `entry` is a `DirEntry`.
1533     ///             println!("{:?}", entry.file_name());
1534     ///         }
1535     ///     }
1536     /// }
1537     /// ```
1538     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1539     pub fn file_name(&self) -> OsString {
1540         self.0.file_name()
1541     }
1542 }
1543
1544 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1545 impl fmt::Debug for DirEntry {
1546     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1547         f.debug_tuple("DirEntry").field(&self.path()).finish()
1548     }
1549 }
1550
1551 impl AsInner<fs_imp::DirEntry> for DirEntry {
1552     fn as_inner(&self) -> &fs_imp::DirEntry {
1553         &self.0
1554     }
1555 }
1556
1557 /// Removes a file from the filesystem.
1558 ///
1559 /// Note that there is no
1560 /// guarantee that the file is immediately deleted (e.g., depending on
1561 /// platform, other open file descriptors may prevent immediate removal).
1562 ///
1563 /// # Platform-specific behavior
1564 ///
1565 /// This function currently corresponds to the `unlink` function on Unix
1566 /// and the `DeleteFile` function on Windows.
1567 /// Note that, this [may change in the future][changes].
1568 ///
1569 /// [changes]: ../io/index.html#platform-specific-behavior
1570 ///
1571 /// # Errors
1572 ///
1573 /// This function will return an error in the following situations, but is not
1574 /// limited to just these cases:
1575 ///
1576 /// * `path` points to a directory.
1577 /// * The file doesn't exist.
1578 /// * The user lacks permissions to remove the file.
1579 ///
1580 /// # Examples
1581 ///
1582 /// ```no_run
1583 /// use std::fs;
1584 ///
1585 /// fn main() -> std::io::Result<()> {
1586 ///     fs::remove_file("a.txt")?;
1587 ///     Ok(())
1588 /// }
1589 /// ```
1590 #[stable(feature = "rust1", since = "1.0.0")]
1591 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1592     fs_imp::unlink(path.as_ref())
1593 }
1594
1595 /// Given a path, query the file system to get information about a file,
1596 /// directory, etc.
1597 ///
1598 /// This function will traverse symbolic links to query information about the
1599 /// destination file.
1600 ///
1601 /// # Platform-specific behavior
1602 ///
1603 /// This function currently corresponds to the `stat` function on Unix
1604 /// and the `GetFileAttributesEx` function on Windows.
1605 /// Note that, this [may change in the future][changes].
1606 ///
1607 /// [changes]: ../io/index.html#platform-specific-behavior
1608 ///
1609 /// # Errors
1610 ///
1611 /// This function will return an error in the following situations, but is not
1612 /// limited to just these cases:
1613 ///
1614 /// * The user lacks permissions to perform `metadata` call on `path`.
1615 /// * `path` does not exist.
1616 ///
1617 /// # Examples
1618 ///
1619 /// ```rust,no_run
1620 /// use std::fs;
1621 ///
1622 /// fn main() -> std::io::Result<()> {
1623 ///     let attr = fs::metadata("/some/file/path.txt")?;
1624 ///     // inspect attr ...
1625 ///     Ok(())
1626 /// }
1627 /// ```
1628 #[stable(feature = "rust1", since = "1.0.0")]
1629 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1630     fs_imp::stat(path.as_ref()).map(Metadata)
1631 }
1632
1633 /// Query the metadata about a file without following symlinks.
1634 ///
1635 /// # Platform-specific behavior
1636 ///
1637 /// This function currently corresponds to the `lstat` function on Unix
1638 /// and the `GetFileAttributesEx` function on Windows.
1639 /// Note that, this [may change in the future][changes].
1640 ///
1641 /// [changes]: ../io/index.html#platform-specific-behavior
1642 ///
1643 /// # Errors
1644 ///
1645 /// This function will return an error in the following situations, but is not
1646 /// limited to just these cases:
1647 ///
1648 /// * The user lacks permissions to perform `metadata` call on `path`.
1649 /// * `path` does not exist.
1650 ///
1651 /// # Examples
1652 ///
1653 /// ```rust,no_run
1654 /// use std::fs;
1655 ///
1656 /// fn main() -> std::io::Result<()> {
1657 ///     let attr = fs::symlink_metadata("/some/file/path.txt")?;
1658 ///     // inspect attr ...
1659 ///     Ok(())
1660 /// }
1661 /// ```
1662 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1663 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1664     fs_imp::lstat(path.as_ref()).map(Metadata)
1665 }
1666
1667 /// Rename a file or directory to a new name, replacing the original file if
1668 /// `to` already exists.
1669 ///
1670 /// This will not work if the new name is on a different mount point.
1671 ///
1672 /// # Platform-specific behavior
1673 ///
1674 /// This function currently corresponds to the `rename` function on Unix
1675 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1676 ///
1677 /// Because of this, the behavior when both `from` and `to` exist differs. On
1678 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1679 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1680 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1681 ///
1682 /// Note that, this [may change in the future][changes].
1683 ///
1684 /// [changes]: ../io/index.html#platform-specific-behavior
1685 ///
1686 /// # Errors
1687 ///
1688 /// This function will return an error in the following situations, but is not
1689 /// limited to just these cases:
1690 ///
1691 /// * `from` does not exist.
1692 /// * The user lacks permissions to view contents.
1693 /// * `from` and `to` are on separate filesystems.
1694 ///
1695 /// # Examples
1696 ///
1697 /// ```no_run
1698 /// use std::fs;
1699 ///
1700 /// fn main() -> std::io::Result<()> {
1701 ///     fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1702 ///     Ok(())
1703 /// }
1704 /// ```
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1707     fs_imp::rename(from.as_ref(), to.as_ref())
1708 }
1709
1710 /// Copies the contents of one file to another. This function will also
1711 /// copy the permission bits of the original file to the destination file.
1712 ///
1713 /// This function will **overwrite** the contents of `to`.
1714 ///
1715 /// Note that if `from` and `to` both point to the same file, then the file
1716 /// will likely get truncated by this operation.
1717 ///
1718 /// On success, the total number of bytes copied is returned and it is equal to
1719 /// the length of the `to` file as reported by `metadata`.
1720 ///
1721 /// If you’re wanting to copy the contents of one file to another and you’re
1722 /// working with [`File`]s, see the [`io::copy`] function.
1723 ///
1724 /// [`io::copy`]: ../io/fn.copy.html
1725 /// [`File`]: ./struct.File.html
1726 ///
1727 /// # Platform-specific behavior
1728 ///
1729 /// This function currently corresponds to the `open` function in Unix
1730 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1731 /// `O_CLOEXEC` is set for returned file descriptors.
1732 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1733 /// NTFS streams are copied but only the size of the main stream is returned by
1734 /// this function. On MacOS, this function corresponds to `fclonefileat` and
1735 /// `fcopyfile`.
1736 /// Note that, this [may change in the future][changes].
1737 ///
1738 /// [changes]: ../io/index.html#platform-specific-behavior
1739 ///
1740 /// # Errors
1741 ///
1742 /// This function will return an error in the following situations, but is not
1743 /// limited to just these cases:
1744 ///
1745 /// * The `from` path is not a file.
1746 /// * The `from` file does not exist.
1747 /// * The current process does not have the permission rights to access
1748 ///   `from` or write `to`.
1749 ///
1750 /// # Examples
1751 ///
1752 /// ```no_run
1753 /// use std::fs;
1754 ///
1755 /// fn main() -> std::io::Result<()> {
1756 ///     fs::copy("foo.txt", "bar.txt")?;  // Copy foo.txt to bar.txt
1757 ///     Ok(())
1758 /// }
1759 /// ```
1760 #[stable(feature = "rust1", since = "1.0.0")]
1761 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1762     fs_imp::copy(from.as_ref(), to.as_ref())
1763 }
1764
1765 /// Creates a new hard link on the filesystem.
1766 ///
1767 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1768 /// often require these two paths to both be located on the same filesystem.
1769 ///
1770 /// # Platform-specific behavior
1771 ///
1772 /// This function currently corresponds to the `link` function on Unix
1773 /// and the `CreateHardLink` function on Windows.
1774 /// Note that, this [may change in the future][changes].
1775 ///
1776 /// [changes]: ../io/index.html#platform-specific-behavior
1777 ///
1778 /// # Errors
1779 ///
1780 /// This function will return an error in the following situations, but is not
1781 /// limited to just these cases:
1782 ///
1783 /// * The `src` path is not a file or doesn't exist.
1784 ///
1785 /// # Examples
1786 ///
1787 /// ```no_run
1788 /// use std::fs;
1789 ///
1790 /// fn main() -> std::io::Result<()> {
1791 ///     fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1792 ///     Ok(())
1793 /// }
1794 /// ```
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1797     fs_imp::link(src.as_ref(), dst.as_ref())
1798 }
1799
1800 /// Creates a new symbolic link on the filesystem.
1801 ///
1802 /// The `dst` path will be a symbolic link pointing to the `src` path.
1803 /// On Windows, this will be a file symlink, not a directory symlink;
1804 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1805 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1806 /// used instead to make the intent explicit.
1807 ///
1808 /// [`std::os::unix::fs::symlink`]: ../os/unix/fs/fn.symlink.html
1809 /// [`std::os::windows::fs::symlink_file`]: ../os/windows/fs/fn.symlink_file.html
1810 /// [`symlink_dir`]: ../os/windows/fs/fn.symlink_dir.html
1811 ///
1812 ///
1813 /// # Examples
1814 ///
1815 /// ```no_run
1816 /// use std::fs;
1817 ///
1818 /// fn main() -> std::io::Result<()> {
1819 ///     fs::soft_link("a.txt", "b.txt")?;
1820 ///     Ok(())
1821 /// }
1822 /// ```
1823 #[stable(feature = "rust1", since = "1.0.0")]
1824 #[rustc_deprecated(
1825     since = "1.1.0",
1826     reason = "replaced with std::os::unix::fs::symlink and \
1827               std::os::windows::fs::{symlink_file, symlink_dir}"
1828 )]
1829 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1830     fs_imp::symlink(src.as_ref(), dst.as_ref())
1831 }
1832
1833 /// Reads a symbolic link, returning the file that the link points to.
1834 ///
1835 /// # Platform-specific behavior
1836 ///
1837 /// This function currently corresponds to the `readlink` function on Unix
1838 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1839 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1840 /// Note that, this [may change in the future][changes].
1841 ///
1842 /// [changes]: ../io/index.html#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 /// * `path` is not a symbolic link.
1850 /// * `path` does not exist.
1851 ///
1852 /// # Examples
1853 ///
1854 /// ```no_run
1855 /// use std::fs;
1856 ///
1857 /// fn main() -> std::io::Result<()> {
1858 ///     let path = fs::read_link("a.txt")?;
1859 ///     Ok(())
1860 /// }
1861 /// ```
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1864     fs_imp::readlink(path.as_ref())
1865 }
1866
1867 /// Returns the canonical, absolute form of a path with all intermediate
1868 /// components normalized and symbolic links resolved.
1869 ///
1870 /// # Platform-specific behavior
1871 ///
1872 /// This function currently corresponds to the `realpath` function on Unix
1873 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1874 /// Note that, this [may change in the future][changes].
1875 ///
1876 /// On Windows, this converts the path to use [extended length path][path]
1877 /// syntax, which allows your program to use longer path names, but means you
1878 /// can only join backslash-delimited paths to it, and it may be incompatible
1879 /// with other applications (if passed to the application on the command-line,
1880 /// or written to a file another application may read).
1881 ///
1882 /// [changes]: ../io/index.html#platform-specific-behavior
1883 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1884 ///
1885 /// # Errors
1886 ///
1887 /// This function will return an error in the following situations, but is not
1888 /// limited to just these cases:
1889 ///
1890 /// * `path` does not exist.
1891 /// * A non-final component in path is not a directory.
1892 ///
1893 /// # Examples
1894 ///
1895 /// ```no_run
1896 /// use std::fs;
1897 ///
1898 /// fn main() -> std::io::Result<()> {
1899 ///     let path = fs::canonicalize("../a/../foo.txt")?;
1900 ///     Ok(())
1901 /// }
1902 /// ```
1903 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1904 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1905     fs_imp::canonicalize(path.as_ref())
1906 }
1907
1908 /// Creates a new, empty directory at the provided path
1909 ///
1910 /// # Platform-specific behavior
1911 ///
1912 /// This function currently corresponds to the `mkdir` function on Unix
1913 /// and the `CreateDirectory` function on Windows.
1914 /// Note that, this [may change in the future][changes].
1915 ///
1916 /// [changes]: ../io/index.html#platform-specific-behavior
1917 ///
1918 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1919 /// return an error. To create a directory and all its missing parents at the
1920 /// same time, use the [`create_dir_all`] function.
1921 ///
1922 /// # Errors
1923 ///
1924 /// This function will return an error in the following situations, but is not
1925 /// limited to just these cases:
1926 ///
1927 /// * User lacks permissions to create directory at `path`.
1928 /// * A parent of the given path doesn't exist. (To create a directory and all
1929 ///   its missing parents at the same time, use the [`create_dir_all`]
1930 ///   function.)
1931 /// * `path` already exists.
1932 ///
1933 /// [`create_dir_all`]: fn.create_dir_all.html
1934 ///
1935 /// # Examples
1936 ///
1937 /// ```no_run
1938 /// use std::fs;
1939 ///
1940 /// fn main() -> std::io::Result<()> {
1941 ///     fs::create_dir("/some/dir")?;
1942 ///     Ok(())
1943 /// }
1944 /// ```
1945 #[stable(feature = "rust1", since = "1.0.0")]
1946 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1947     DirBuilder::new().create(path.as_ref())
1948 }
1949
1950 /// Recursively create a directory and all of its parent components if they
1951 /// are missing.
1952 ///
1953 /// # Platform-specific behavior
1954 ///
1955 /// This function currently corresponds to the `mkdir` function on Unix
1956 /// and the `CreateDirectory` function on Windows.
1957 /// Note that, this [may change in the future][changes].
1958 ///
1959 /// [changes]: ../io/index.html#platform-specific-behavior
1960 ///
1961 /// # Errors
1962 ///
1963 /// This function will return an error in the following situations, but is not
1964 /// limited to just these cases:
1965 ///
1966 /// * If any directory in the path specified by `path`
1967 /// does not already exist and it could not be created otherwise. The specific
1968 /// error conditions for when a directory is being created (after it is
1969 /// determined to not exist) are outlined by [`fs::create_dir`].
1970 ///
1971 /// Notable exception is made for situations where any of the directories
1972 /// specified in the `path` could not be created as it was being created concurrently.
1973 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1974 /// concurrently from multiple threads or processes is guaranteed not to fail
1975 /// due to a race condition with itself.
1976 ///
1977 /// [`fs::create_dir`]: fn.create_dir.html
1978 ///
1979 /// # Examples
1980 ///
1981 /// ```no_run
1982 /// use std::fs;
1983 ///
1984 /// fn main() -> std::io::Result<()> {
1985 ///     fs::create_dir_all("/some/dir")?;
1986 ///     Ok(())
1987 /// }
1988 /// ```
1989 #[stable(feature = "rust1", since = "1.0.0")]
1990 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1991     DirBuilder::new().recursive(true).create(path.as_ref())
1992 }
1993
1994 /// Removes an existing, empty directory.
1995 ///
1996 /// # Platform-specific behavior
1997 ///
1998 /// This function currently corresponds to the `rmdir` function on Unix
1999 /// and the `RemoveDirectory` function on Windows.
2000 /// Note that, this [may change in the future][changes].
2001 ///
2002 /// [changes]: ../io/index.html#platform-specific-behavior
2003 ///
2004 /// # Errors
2005 ///
2006 /// This function will return an error in the following situations, but is not
2007 /// limited to just these cases:
2008 ///
2009 /// * The user lacks permissions to remove the directory at the provided `path`.
2010 /// * The directory isn't empty.
2011 ///
2012 /// # Examples
2013 ///
2014 /// ```no_run
2015 /// use std::fs;
2016 ///
2017 /// fn main() -> std::io::Result<()> {
2018 ///     fs::remove_dir("/some/dir")?;
2019 ///     Ok(())
2020 /// }
2021 /// ```
2022 #[stable(feature = "rust1", since = "1.0.0")]
2023 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2024     fs_imp::rmdir(path.as_ref())
2025 }
2026
2027 /// Removes a directory at this path, after removing all its contents. Use
2028 /// carefully!
2029 ///
2030 /// This function does **not** follow symbolic links and it will simply remove the
2031 /// symbolic link itself.
2032 ///
2033 /// # Platform-specific behavior
2034 ///
2035 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
2036 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
2037 /// on Windows.
2038 /// Note that, this [may change in the future][changes].
2039 ///
2040 /// [changes]: ../io/index.html#platform-specific-behavior
2041 ///
2042 /// # Errors
2043 ///
2044 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2045 ///
2046 /// [`fs::remove_file`]:  fn.remove_file.html
2047 /// [`fs::remove_dir`]: fn.remove_dir.html
2048 ///
2049 /// # Examples
2050 ///
2051 /// ```no_run
2052 /// use std::fs;
2053 ///
2054 /// fn main() -> std::io::Result<()> {
2055 ///     fs::remove_dir_all("/some/dir")?;
2056 ///     Ok(())
2057 /// }
2058 /// ```
2059 #[stable(feature = "rust1", since = "1.0.0")]
2060 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2061     fs_imp::remove_dir_all(path.as_ref())
2062 }
2063
2064 /// Returns an iterator over the entries within a directory.
2065 ///
2066 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
2067 /// New errors may be encountered after an iterator is initially constructed.
2068 ///
2069 /// [`io::Result`]: ../io/type.Result.html
2070 /// [`DirEntry`]: struct.DirEntry.html
2071 ///
2072 /// # Platform-specific behavior
2073 ///
2074 /// This function currently corresponds to the `opendir` function on Unix
2075 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2076 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2077 /// Note that, this [may change in the future][changes].
2078 ///
2079 /// [changes]: ../io/index.html#platform-specific-behavior
2080 ///
2081 /// The order in which this iterator returns entries is platform and filesystem
2082 /// dependent.
2083 ///
2084 /// # Errors
2085 ///
2086 /// This function will return an error in the following situations, but is not
2087 /// limited to just these cases:
2088 ///
2089 /// * The provided `path` doesn't exist.
2090 /// * The process lacks permissions to view the contents.
2091 /// * The `path` points at a non-directory file.
2092 ///
2093 /// # Examples
2094 ///
2095 /// ```
2096 /// use std::io;
2097 /// use std::fs::{self, DirEntry};
2098 /// use std::path::Path;
2099 ///
2100 /// // one possible implementation of walking a directory only visiting files
2101 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2102 ///     if dir.is_dir() {
2103 ///         for entry in fs::read_dir(dir)? {
2104 ///             let entry = entry?;
2105 ///             let path = entry.path();
2106 ///             if path.is_dir() {
2107 ///                 visit_dirs(&path, cb)?;
2108 ///             } else {
2109 ///                 cb(&entry);
2110 ///             }
2111 ///         }
2112 ///     }
2113 ///     Ok(())
2114 /// }
2115 /// ```
2116 ///
2117 /// ```rust,no_run
2118 /// use std::{fs, io};
2119 ///
2120 /// fn main() -> io::Result<()> {
2121 ///     let mut entries = fs::read_dir(".")?
2122 ///         .map(|res| res.map(|e| e.path()))
2123 ///         .collect::<Result<Vec<_>, io::Error>>()?;
2124 ///
2125 ///     // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2126 ///     // ordering is required the entries should be explicitly sorted.
2127 ///
2128 ///     entries.sort();
2129 ///
2130 ///     // The entries have now been sorted by their path.
2131 ///
2132 ///     Ok(())
2133 /// }
2134 /// ```
2135 #[stable(feature = "rust1", since = "1.0.0")]
2136 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2137     fs_imp::readdir(path.as_ref()).map(ReadDir)
2138 }
2139
2140 /// Changes the permissions found on a file or a directory.
2141 ///
2142 /// # Platform-specific behavior
2143 ///
2144 /// This function currently corresponds to the `chmod` function on Unix
2145 /// and the `SetFileAttributes` function on Windows.
2146 /// Note that, this [may change in the future][changes].
2147 ///
2148 /// [changes]: ../io/index.html#platform-specific-behavior
2149 ///
2150 /// # Errors
2151 ///
2152 /// This function will return an error in the following situations, but is not
2153 /// limited to just these cases:
2154 ///
2155 /// * `path` does not exist.
2156 /// * The user lacks the permission to change attributes of the file.
2157 ///
2158 /// # Examples
2159 ///
2160 /// ```no_run
2161 /// use std::fs;
2162 ///
2163 /// fn main() -> std::io::Result<()> {
2164 ///     let mut perms = fs::metadata("foo.txt")?.permissions();
2165 ///     perms.set_readonly(true);
2166 ///     fs::set_permissions("foo.txt", perms)?;
2167 ///     Ok(())
2168 /// }
2169 /// ```
2170 #[stable(feature = "set_permissions", since = "1.1.0")]
2171 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2172     fs_imp::set_perm(path.as_ref(), perm.0)
2173 }
2174
2175 impl DirBuilder {
2176     /// Creates a new set of options with default mode/security settings for all
2177     /// platforms and also non-recursive.
2178     ///
2179     /// # Examples
2180     ///
2181     /// ```
2182     /// use std::fs::DirBuilder;
2183     ///
2184     /// let builder = DirBuilder::new();
2185     /// ```
2186     #[stable(feature = "dir_builder", since = "1.6.0")]
2187     pub fn new() -> DirBuilder {
2188         DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2189     }
2190
2191     /// Indicates that directories should be created recursively, creating all
2192     /// parent directories. Parents that do not exist are created with the same
2193     /// security and permissions settings.
2194     ///
2195     /// This option defaults to `false`.
2196     ///
2197     /// # Examples
2198     ///
2199     /// ```
2200     /// use std::fs::DirBuilder;
2201     ///
2202     /// let mut builder = DirBuilder::new();
2203     /// builder.recursive(true);
2204     /// ```
2205     #[stable(feature = "dir_builder", since = "1.6.0")]
2206     pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2207         self.recursive = recursive;
2208         self
2209     }
2210
2211     /// Creates the specified directory with the options configured in this
2212     /// builder.
2213     ///
2214     /// It is considered an error if the directory already exists unless
2215     /// recursive mode is enabled.
2216     ///
2217     /// # Examples
2218     ///
2219     /// ```no_run
2220     /// use std::fs::{self, DirBuilder};
2221     ///
2222     /// let path = "/tmp/foo/bar/baz";
2223     /// DirBuilder::new()
2224     ///     .recursive(true)
2225     ///     .create(path).unwrap();
2226     ///
2227     /// assert!(fs::metadata(path).unwrap().is_dir());
2228     /// ```
2229     #[stable(feature = "dir_builder", since = "1.6.0")]
2230     pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2231         self._create(path.as_ref())
2232     }
2233
2234     fn _create(&self, path: &Path) -> io::Result<()> {
2235         if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2236     }
2237
2238     fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2239         if path == Path::new("") {
2240             return Ok(());
2241         }
2242
2243         match self.inner.mkdir(path) {
2244             Ok(()) => return Ok(()),
2245             Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2246             Err(_) if path.is_dir() => return Ok(()),
2247             Err(e) => return Err(e),
2248         }
2249         match path.parent() {
2250             Some(p) => self.create_dir_all(p)?,
2251             None => {
2252                 return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree"));
2253             }
2254         }
2255         match self.inner.mkdir(path) {
2256             Ok(()) => Ok(()),
2257             Err(_) if path.is_dir() => Ok(()),
2258             Err(e) => Err(e),
2259         }
2260     }
2261 }
2262
2263 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2264     fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2265         &mut self.inner
2266     }
2267 }
2268
2269 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
2270 mod tests {
2271     use crate::io::prelude::*;
2272
2273     use crate::fs::{self, File, OpenOptions};
2274     use crate::io::{ErrorKind, SeekFrom};
2275     use crate::path::Path;
2276     use crate::str;
2277     use crate::sys_common::io::test::{tmpdir, TempDir};
2278     use crate::thread;
2279
2280     use rand::{rngs::StdRng, RngCore, SeedableRng};
2281
2282     #[cfg(unix)]
2283     use crate::os::unix::fs::symlink as symlink_dir;
2284     #[cfg(unix)]
2285     use crate::os::unix::fs::symlink as symlink_file;
2286     #[cfg(unix)]
2287     use crate::os::unix::fs::symlink as symlink_junction;
2288     #[cfg(windows)]
2289     use crate::os::windows::fs::{symlink_dir, symlink_file};
2290     #[cfg(windows)]
2291     use crate::sys::fs::symlink_junction;
2292
2293     macro_rules! check {
2294         ($e:expr) => {
2295             match $e {
2296                 Ok(t) => t,
2297                 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
2298             }
2299         };
2300     }
2301
2302     #[cfg(windows)]
2303     macro_rules! error {
2304         ($e:expr, $s:expr) => {
2305             match $e {
2306                 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2307                 Err(ref err) => assert!(
2308                     err.raw_os_error() == Some($s),
2309                     format!("`{}` did not have a code of `{}`", err, $s)
2310                 ),
2311             }
2312         };
2313     }
2314
2315     #[cfg(unix)]
2316     macro_rules! error {
2317         ($e:expr, $s:expr) => {
2318             error_contains!($e, $s)
2319         };
2320     }
2321
2322     macro_rules! error_contains {
2323         ($e:expr, $s:expr) => {
2324             match $e {
2325                 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2326                 Err(ref err) => assert!(
2327                     err.to_string().contains($s),
2328                     format!("`{}` did not contain `{}`", err, $s)
2329                 ),
2330             }
2331         };
2332     }
2333
2334     // Several test fail on windows if the user does not have permission to
2335     // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
2336     // disabling these test on Windows, use this function to test whether we
2337     // have permission, and return otherwise. This way, we still don't run these
2338     // tests most of the time, but at least we do if the user has the right
2339     // permissions.
2340     pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
2341         if cfg!(unix) {
2342             return true;
2343         }
2344         let link = tmpdir.join("some_hopefully_unique_link_name");
2345
2346         match symlink_file(r"nonexisting_target", link) {
2347             Ok(_) => true,
2348             // ERROR_PRIVILEGE_NOT_HELD = 1314
2349             Err(ref err) if err.raw_os_error() == Some(1314) => false,
2350             Err(_) => true,
2351         }
2352     }
2353
2354     #[test]
2355     fn file_test_io_smoke_test() {
2356         let message = "it's alright. have a good time";
2357         let tmpdir = tmpdir();
2358         let filename = &tmpdir.join("file_rt_io_file_test.txt");
2359         {
2360             let mut write_stream = check!(File::create(filename));
2361             check!(write_stream.write(message.as_bytes()));
2362         }
2363         {
2364             let mut read_stream = check!(File::open(filename));
2365             let mut read_buf = [0; 1028];
2366             let read_str = match check!(read_stream.read(&mut read_buf)) {
2367                 0 => panic!("shouldn't happen"),
2368                 n => str::from_utf8(&read_buf[..n]).unwrap().to_string(),
2369             };
2370             assert_eq!(read_str, message);
2371         }
2372         check!(fs::remove_file(filename));
2373     }
2374
2375     #[test]
2376     fn invalid_path_raises() {
2377         let tmpdir = tmpdir();
2378         let filename = &tmpdir.join("file_that_does_not_exist.txt");
2379         let result = File::open(filename);
2380
2381         #[cfg(all(unix, not(target_os = "vxworks")))]
2382         error!(result, "No such file or directory");
2383         #[cfg(target_os = "vxworks")]
2384         error!(result, "no such file or directory");
2385         #[cfg(windows)]
2386         error!(result, 2); // ERROR_FILE_NOT_FOUND
2387     }
2388
2389     #[test]
2390     fn file_test_iounlinking_invalid_path_should_raise_condition() {
2391         let tmpdir = tmpdir();
2392         let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
2393
2394         let result = fs::remove_file(filename);
2395
2396         #[cfg(all(unix, not(target_os = "vxworks")))]
2397         error!(result, "No such file or directory");
2398         #[cfg(target_os = "vxworks")]
2399         error!(result, "no such file or directory");
2400         #[cfg(windows)]
2401         error!(result, 2); // ERROR_FILE_NOT_FOUND
2402     }
2403
2404     #[test]
2405     fn file_test_io_non_positional_read() {
2406         let message: &str = "ten-four";
2407         let mut read_mem = [0; 8];
2408         let tmpdir = tmpdir();
2409         let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
2410         {
2411             let mut rw_stream = check!(File::create(filename));
2412             check!(rw_stream.write(message.as_bytes()));
2413         }
2414         {
2415             let mut read_stream = check!(File::open(filename));
2416             {
2417                 let read_buf = &mut read_mem[0..4];
2418                 check!(read_stream.read(read_buf));
2419             }
2420             {
2421                 let read_buf = &mut read_mem[4..8];
2422                 check!(read_stream.read(read_buf));
2423             }
2424         }
2425         check!(fs::remove_file(filename));
2426         let read_str = str::from_utf8(&read_mem).unwrap();
2427         assert_eq!(read_str, message);
2428     }
2429
2430     #[test]
2431     fn file_test_io_seek_and_tell_smoke_test() {
2432         let message = "ten-four";
2433         let mut read_mem = [0; 4];
2434         let set_cursor = 4 as u64;
2435         let tell_pos_pre_read;
2436         let tell_pos_post_read;
2437         let tmpdir = tmpdir();
2438         let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
2439         {
2440             let mut rw_stream = check!(File::create(filename));
2441             check!(rw_stream.write(message.as_bytes()));
2442         }
2443         {
2444             let mut read_stream = check!(File::open(filename));
2445             check!(read_stream.seek(SeekFrom::Start(set_cursor)));
2446             tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
2447             check!(read_stream.read(&mut read_mem));
2448             tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
2449         }
2450         check!(fs::remove_file(filename));
2451         let read_str = str::from_utf8(&read_mem).unwrap();
2452         assert_eq!(read_str, &message[4..8]);
2453         assert_eq!(tell_pos_pre_read, set_cursor);
2454         assert_eq!(tell_pos_post_read, message.len() as u64);
2455     }
2456
2457     #[test]
2458     fn file_test_io_seek_and_write() {
2459         let initial_msg = "food-is-yummy";
2460         let overwrite_msg = "-the-bar!!";
2461         let final_msg = "foo-the-bar!!";
2462         let seek_idx = 3;
2463         let mut read_mem = [0; 13];
2464         let tmpdir = tmpdir();
2465         let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
2466         {
2467             let mut rw_stream = check!(File::create(filename));
2468             check!(rw_stream.write(initial_msg.as_bytes()));
2469             check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
2470             check!(rw_stream.write(overwrite_msg.as_bytes()));
2471         }
2472         {
2473             let mut read_stream = check!(File::open(filename));
2474             check!(read_stream.read(&mut read_mem));
2475         }
2476         check!(fs::remove_file(filename));
2477         let read_str = str::from_utf8(&read_mem).unwrap();
2478         assert!(read_str == final_msg);
2479     }
2480
2481     #[test]
2482     fn file_test_io_seek_shakedown() {
2483         //                   01234567890123
2484         let initial_msg = "qwer-asdf-zxcv";
2485         let chunk_one: &str = "qwer";
2486         let chunk_two: &str = "asdf";
2487         let chunk_three: &str = "zxcv";
2488         let mut read_mem = [0; 4];
2489         let tmpdir = tmpdir();
2490         let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2491         {
2492             let mut rw_stream = check!(File::create(filename));
2493             check!(rw_stream.write(initial_msg.as_bytes()));
2494         }
2495         {
2496             let mut read_stream = check!(File::open(filename));
2497
2498             check!(read_stream.seek(SeekFrom::End(-4)));
2499             check!(read_stream.read(&mut read_mem));
2500             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2501
2502             check!(read_stream.seek(SeekFrom::Current(-9)));
2503             check!(read_stream.read(&mut read_mem));
2504             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2505
2506             check!(read_stream.seek(SeekFrom::Start(0)));
2507             check!(read_stream.read(&mut read_mem));
2508             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2509         }
2510         check!(fs::remove_file(filename));
2511     }
2512
2513     #[test]
2514     fn file_test_io_eof() {
2515         let tmpdir = tmpdir();
2516         let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2517         let mut buf = [0; 256];
2518         {
2519             let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2520             let mut rw = check!(oo.open(&filename));
2521             assert_eq!(check!(rw.read(&mut buf)), 0);
2522             assert_eq!(check!(rw.read(&mut buf)), 0);
2523         }
2524         check!(fs::remove_file(&filename));
2525     }
2526
2527     #[test]
2528     #[cfg(unix)]
2529     fn file_test_io_read_write_at() {
2530         use crate::os::unix::fs::FileExt;
2531
2532         let tmpdir = tmpdir();
2533         let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2534         let mut buf = [0; 256];
2535         let write1 = "asdf";
2536         let write2 = "qwer-";
2537         let write3 = "-zxcv";
2538         let content = "qwer-asdf-zxcv";
2539         {
2540             let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2541             let mut rw = check!(oo.open(&filename));
2542             assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2543             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2544             assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2545             assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2546             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2547             assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2548             assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2549             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2550             assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2551             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2552             assert_eq!(check!(rw.read(&mut buf)), write1.len());
2553             assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2554             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2555             assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2556             assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2557             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2558             assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2559             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2560         }
2561         {
2562             let mut read = check!(File::open(&filename));
2563             assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2564             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2565             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2566             assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2567             assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2568             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2569             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2570             assert_eq!(check!(read.read(&mut buf)), write3.len());
2571             assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2572             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2573             assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2574             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2575             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2576             assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2577             assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2578             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2579         }
2580         check!(fs::remove_file(&filename));
2581     }
2582
2583     #[test]
2584     #[cfg(unix)]
2585     fn set_get_unix_permissions() {
2586         use crate::os::unix::fs::PermissionsExt;
2587
2588         let tmpdir = tmpdir();
2589         let filename = &tmpdir.join("set_get_unix_permissions");
2590         check!(fs::create_dir(filename));
2591         let mask = 0o7777;
2592
2593         check!(fs::set_permissions(filename, fs::Permissions::from_mode(0)));
2594         let metadata0 = check!(fs::metadata(filename));
2595         assert_eq!(mask & metadata0.permissions().mode(), 0);
2596
2597         check!(fs::set_permissions(filename, fs::Permissions::from_mode(0o1777)));
2598         let metadata1 = check!(fs::metadata(filename));
2599         #[cfg(all(unix, not(target_os = "vxworks")))]
2600         assert_eq!(mask & metadata1.permissions().mode(), 0o1777);
2601         #[cfg(target_os = "vxworks")]
2602         assert_eq!(mask & metadata1.permissions().mode(), 0o0777);
2603     }
2604
2605     #[test]
2606     #[cfg(windows)]
2607     fn file_test_io_seek_read_write() {
2608         use crate::os::windows::fs::FileExt;
2609
2610         let tmpdir = tmpdir();
2611         let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2612         let mut buf = [0; 256];
2613         let write1 = "asdf";
2614         let write2 = "qwer-";
2615         let write3 = "-zxcv";
2616         let content = "qwer-asdf-zxcv";
2617         {
2618             let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2619             let mut rw = check!(oo.open(&filename));
2620             assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2621             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2622             assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2623             assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2624             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2625             assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2626             assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2627             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2628             assert_eq!(check!(rw.read(&mut buf)), write1.len());
2629             assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2630             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2631             assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2632             assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2633             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2634             assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2635             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2636         }
2637         {
2638             let mut read = check!(File::open(&filename));
2639             assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2640             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2641             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2642             assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2643             assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2644             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2645             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2646             assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2647             assert_eq!(check!(read.read(&mut buf)), write3.len());
2648             assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2649             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2650             assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2651             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2652             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2653             assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2654             assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2655         }
2656         check!(fs::remove_file(&filename));
2657     }
2658
2659     #[test]
2660     fn file_test_stat_is_correct_on_is_file() {
2661         let tmpdir = tmpdir();
2662         let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2663         {
2664             let mut opts = OpenOptions::new();
2665             let mut fs = check!(opts.read(true).write(true).create(true).open(filename));
2666             let msg = "hw";
2667             fs.write(msg.as_bytes()).unwrap();
2668
2669             let fstat_res = check!(fs.metadata());
2670             assert!(fstat_res.is_file());
2671         }
2672         let stat_res_fn = check!(fs::metadata(filename));
2673         assert!(stat_res_fn.is_file());
2674         let stat_res_meth = check!(filename.metadata());
2675         assert!(stat_res_meth.is_file());
2676         check!(fs::remove_file(filename));
2677     }
2678
2679     #[test]
2680     fn file_test_stat_is_correct_on_is_dir() {
2681         let tmpdir = tmpdir();
2682         let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2683         check!(fs::create_dir(filename));
2684         let stat_res_fn = check!(fs::metadata(filename));
2685         assert!(stat_res_fn.is_dir());
2686         let stat_res_meth = check!(filename.metadata());
2687         assert!(stat_res_meth.is_dir());
2688         check!(fs::remove_dir(filename));
2689     }
2690
2691     #[test]
2692     fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2693         let tmpdir = tmpdir();
2694         let dir = &tmpdir.join("fileinfo_false_on_dir");
2695         check!(fs::create_dir(dir));
2696         assert!(!dir.is_file());
2697         check!(fs::remove_dir(dir));
2698     }
2699
2700     #[test]
2701     fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2702         let tmpdir = tmpdir();
2703         let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2704         check!(check!(File::create(file)).write(b"foo"));
2705         assert!(file.exists());
2706         check!(fs::remove_file(file));
2707         assert!(!file.exists());
2708     }
2709
2710     #[test]
2711     fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2712         let tmpdir = tmpdir();
2713         let dir = &tmpdir.join("before_and_after_dir");
2714         assert!(!dir.exists());
2715         check!(fs::create_dir(dir));
2716         assert!(dir.exists());
2717         assert!(dir.is_dir());
2718         check!(fs::remove_dir(dir));
2719         assert!(!dir.exists());
2720     }
2721
2722     #[test]
2723     fn file_test_directoryinfo_readdir() {
2724         let tmpdir = tmpdir();
2725         let dir = &tmpdir.join("di_readdir");
2726         check!(fs::create_dir(dir));
2727         let prefix = "foo";
2728         for n in 0..3 {
2729             let f = dir.join(&format!("{}.txt", n));
2730             let mut w = check!(File::create(&f));
2731             let msg_str = format!("{}{}", prefix, n.to_string());
2732             let msg = msg_str.as_bytes();
2733             check!(w.write(msg));
2734         }
2735         let files = check!(fs::read_dir(dir));
2736         let mut mem = [0; 4];
2737         for f in files {
2738             let f = f.unwrap().path();
2739             {
2740                 let n = f.file_stem().unwrap();
2741                 check!(check!(File::open(&f)).read(&mut mem));
2742                 let read_str = str::from_utf8(&mem).unwrap();
2743                 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2744                 assert_eq!(expected, read_str);
2745             }
2746             check!(fs::remove_file(&f));
2747         }
2748         check!(fs::remove_dir(dir));
2749     }
2750
2751     #[test]
2752     fn file_create_new_already_exists_error() {
2753         let tmpdir = tmpdir();
2754         let file = &tmpdir.join("file_create_new_error_exists");
2755         check!(fs::File::create(file));
2756         let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2757         assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2758     }
2759
2760     #[test]
2761     fn mkdir_path_already_exists_error() {
2762         let tmpdir = tmpdir();
2763         let dir = &tmpdir.join("mkdir_error_twice");
2764         check!(fs::create_dir(dir));
2765         let e = fs::create_dir(dir).unwrap_err();
2766         assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2767     }
2768
2769     #[test]
2770     fn recursive_mkdir() {
2771         let tmpdir = tmpdir();
2772         let dir = tmpdir.join("d1/d2");
2773         check!(fs::create_dir_all(&dir));
2774         assert!(dir.is_dir())
2775     }
2776
2777     #[test]
2778     fn recursive_mkdir_failure() {
2779         let tmpdir = tmpdir();
2780         let dir = tmpdir.join("d1");
2781         let file = dir.join("f1");
2782
2783         check!(fs::create_dir_all(&dir));
2784         check!(File::create(&file));
2785
2786         let result = fs::create_dir_all(&file);
2787
2788         assert!(result.is_err());
2789     }
2790
2791     #[test]
2792     fn concurrent_recursive_mkdir() {
2793         for _ in 0..100 {
2794             let dir = tmpdir();
2795             let mut dir = dir.join("a");
2796             for _ in 0..40 {
2797                 dir = dir.join("a");
2798             }
2799             let mut join = vec![];
2800             for _ in 0..8 {
2801                 let dir = dir.clone();
2802                 join.push(thread::spawn(move || {
2803                     check!(fs::create_dir_all(&dir));
2804                 }))
2805             }
2806
2807             // No `Display` on result of `join()`
2808             join.drain(..).map(|join| join.join().unwrap()).count();
2809         }
2810     }
2811
2812     #[test]
2813     fn recursive_mkdir_slash() {
2814         check!(fs::create_dir_all(Path::new("/")));
2815     }
2816
2817     #[test]
2818     fn recursive_mkdir_dot() {
2819         check!(fs::create_dir_all(Path::new(".")));
2820     }
2821
2822     #[test]
2823     fn recursive_mkdir_empty() {
2824         check!(fs::create_dir_all(Path::new("")));
2825     }
2826
2827     #[test]
2828     fn recursive_rmdir() {
2829         let tmpdir = tmpdir();
2830         let d1 = tmpdir.join("d1");
2831         let dt = d1.join("t");
2832         let dtt = dt.join("t");
2833         let d2 = tmpdir.join("d2");
2834         let canary = d2.join("do_not_delete");
2835         check!(fs::create_dir_all(&dtt));
2836         check!(fs::create_dir_all(&d2));
2837         check!(check!(File::create(&canary)).write(b"foo"));
2838         check!(symlink_junction(&d2, &dt.join("d2")));
2839         let _ = symlink_file(&canary, &d1.join("canary"));
2840         check!(fs::remove_dir_all(&d1));
2841
2842         assert!(!d1.is_dir());
2843         assert!(canary.exists());
2844     }
2845
2846     #[test]
2847     fn recursive_rmdir_of_symlink() {
2848         // test we do not recursively delete a symlink but only dirs.
2849         let tmpdir = tmpdir();
2850         let link = tmpdir.join("d1");
2851         let dir = tmpdir.join("d2");
2852         let canary = dir.join("do_not_delete");
2853         check!(fs::create_dir_all(&dir));
2854         check!(check!(File::create(&canary)).write(b"foo"));
2855         check!(symlink_junction(&dir, &link));
2856         check!(fs::remove_dir_all(&link));
2857
2858         assert!(!link.is_dir());
2859         assert!(canary.exists());
2860     }
2861
2862     #[test]
2863     // only Windows makes a distinction between file and directory symlinks.
2864     #[cfg(windows)]
2865     fn recursive_rmdir_of_file_symlink() {
2866         let tmpdir = tmpdir();
2867         if !got_symlink_permission(&tmpdir) {
2868             return;
2869         };
2870
2871         let f1 = tmpdir.join("f1");
2872         let f2 = tmpdir.join("f2");
2873         check!(check!(File::create(&f1)).write(b"foo"));
2874         check!(symlink_file(&f1, &f2));
2875         match fs::remove_dir_all(&f2) {
2876             Ok(..) => panic!("wanted a failure"),
2877             Err(..) => {}
2878         }
2879     }
2880
2881     #[test]
2882     fn unicode_path_is_dir() {
2883         assert!(Path::new(".").is_dir());
2884         assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2885
2886         let tmpdir = tmpdir();
2887
2888         let mut dirpath = tmpdir.path().to_path_buf();
2889         dirpath.push("test-가一ー你好");
2890         check!(fs::create_dir(&dirpath));
2891         assert!(dirpath.is_dir());
2892
2893         let mut filepath = dirpath;
2894         filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2895         check!(File::create(&filepath)); // ignore return; touch only
2896         assert!(!filepath.is_dir());
2897         assert!(filepath.exists());
2898     }
2899
2900     #[test]
2901     fn unicode_path_exists() {
2902         assert!(Path::new(".").exists());
2903         assert!(!Path::new("test/nonexistent-bogus-path").exists());
2904
2905         let tmpdir = tmpdir();
2906         let unicode = tmpdir.path();
2907         let unicode = unicode.join("test-각丁ー再见");
2908         check!(fs::create_dir(&unicode));
2909         assert!(unicode.exists());
2910         assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2911     }
2912
2913     #[test]
2914     fn copy_file_does_not_exist() {
2915         let from = Path::new("test/nonexistent-bogus-path");
2916         let to = Path::new("test/other-bogus-path");
2917
2918         match fs::copy(&from, &to) {
2919             Ok(..) => panic!(),
2920             Err(..) => {
2921                 assert!(!from.exists());
2922                 assert!(!to.exists());
2923             }
2924         }
2925     }
2926
2927     #[test]
2928     fn copy_src_does_not_exist() {
2929         let tmpdir = tmpdir();
2930         let from = Path::new("test/nonexistent-bogus-path");
2931         let to = tmpdir.join("out.txt");
2932         check!(check!(File::create(&to)).write(b"hello"));
2933         assert!(fs::copy(&from, &to).is_err());
2934         assert!(!from.exists());
2935         let mut v = Vec::new();
2936         check!(check!(File::open(&to)).read_to_end(&mut v));
2937         assert_eq!(v, b"hello");
2938     }
2939
2940     #[test]
2941     fn copy_file_ok() {
2942         let tmpdir = tmpdir();
2943         let input = tmpdir.join("in.txt");
2944         let out = tmpdir.join("out.txt");
2945
2946         check!(check!(File::create(&input)).write(b"hello"));
2947         check!(fs::copy(&input, &out));
2948         let mut v = Vec::new();
2949         check!(check!(File::open(&out)).read_to_end(&mut v));
2950         assert_eq!(v, b"hello");
2951
2952         assert_eq!(check!(input.metadata()).permissions(), check!(out.metadata()).permissions());
2953     }
2954
2955     #[test]
2956     fn copy_file_dst_dir() {
2957         let tmpdir = tmpdir();
2958         let out = tmpdir.join("out");
2959
2960         check!(File::create(&out));
2961         match fs::copy(&*out, tmpdir.path()) {
2962             Ok(..) => panic!(),
2963             Err(..) => {}
2964         }
2965     }
2966
2967     #[test]
2968     fn copy_file_dst_exists() {
2969         let tmpdir = tmpdir();
2970         let input = tmpdir.join("in");
2971         let output = tmpdir.join("out");
2972
2973         check!(check!(File::create(&input)).write("foo".as_bytes()));
2974         check!(check!(File::create(&output)).write("bar".as_bytes()));
2975         check!(fs::copy(&input, &output));
2976
2977         let mut v = Vec::new();
2978         check!(check!(File::open(&output)).read_to_end(&mut v));
2979         assert_eq!(v, b"foo".to_vec());
2980     }
2981
2982     #[test]
2983     fn copy_file_src_dir() {
2984         let tmpdir = tmpdir();
2985         let out = tmpdir.join("out");
2986
2987         match fs::copy(tmpdir.path(), &out) {
2988             Ok(..) => panic!(),
2989             Err(..) => {}
2990         }
2991         assert!(!out.exists());
2992     }
2993
2994     #[test]
2995     fn copy_file_preserves_perm_bits() {
2996         let tmpdir = tmpdir();
2997         let input = tmpdir.join("in.txt");
2998         let out = tmpdir.join("out.txt");
2999
3000         let attr = check!(check!(File::create(&input)).metadata());
3001         let mut p = attr.permissions();
3002         p.set_readonly(true);
3003         check!(fs::set_permissions(&input, p));
3004         check!(fs::copy(&input, &out));
3005         assert!(check!(out.metadata()).permissions().readonly());
3006         check!(fs::set_permissions(&input, attr.permissions()));
3007         check!(fs::set_permissions(&out, attr.permissions()));
3008     }
3009
3010     #[test]
3011     #[cfg(windows)]
3012     fn copy_file_preserves_streams() {
3013         let tmp = tmpdir();
3014         check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
3015         assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 0);
3016         assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
3017         let mut v = Vec::new();
3018         check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
3019         assert_eq!(v, b"carrot".to_vec());
3020     }
3021
3022     #[test]
3023     fn copy_file_returns_metadata_len() {
3024         let tmp = tmpdir();
3025         let in_path = tmp.join("in.txt");
3026         let out_path = tmp.join("out.txt");
3027         check!(check!(File::create(&in_path)).write(b"lettuce"));
3028         #[cfg(windows)]
3029         check!(check!(File::create(tmp.join("in.txt:bunny"))).write(b"carrot"));
3030         let copied_len = check!(fs::copy(&in_path, &out_path));
3031         assert_eq!(check!(out_path.metadata()).len(), copied_len);
3032     }
3033
3034     #[test]
3035     fn copy_file_follows_dst_symlink() {
3036         let tmp = tmpdir();
3037         if !got_symlink_permission(&tmp) {
3038             return;
3039         };
3040
3041         let in_path = tmp.join("in.txt");
3042         let out_path = tmp.join("out.txt");
3043         let out_path_symlink = tmp.join("out_symlink.txt");
3044
3045         check!(fs::write(&in_path, "foo"));
3046         check!(fs::write(&out_path, "bar"));
3047         check!(symlink_file(&out_path, &out_path_symlink));
3048
3049         check!(fs::copy(&in_path, &out_path_symlink));
3050
3051         assert!(check!(out_path_symlink.symlink_metadata()).file_type().is_symlink());
3052         assert_eq!(check!(fs::read(&out_path_symlink)), b"foo".to_vec());
3053         assert_eq!(check!(fs::read(&out_path)), b"foo".to_vec());
3054     }
3055
3056     #[test]
3057     fn symlinks_work() {
3058         let tmpdir = tmpdir();
3059         if !got_symlink_permission(&tmpdir) {
3060             return;
3061         };
3062
3063         let input = tmpdir.join("in.txt");
3064         let out = tmpdir.join("out.txt");
3065
3066         check!(check!(File::create(&input)).write("foobar".as_bytes()));
3067         check!(symlink_file(&input, &out));
3068         assert!(check!(out.symlink_metadata()).file_type().is_symlink());
3069         assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len());
3070         let mut v = Vec::new();
3071         check!(check!(File::open(&out)).read_to_end(&mut v));
3072         assert_eq!(v, b"foobar".to_vec());
3073     }
3074
3075     #[test]
3076     fn symlink_noexist() {
3077         // Symlinks can point to things that don't exist
3078         let tmpdir = tmpdir();
3079         if !got_symlink_permission(&tmpdir) {
3080             return;
3081         };
3082
3083         // Use a relative path for testing. Symlinks get normalized by Windows,
3084         // so we may not get the same path back for absolute paths
3085         check!(symlink_file(&"foo", &tmpdir.join("bar")));
3086         assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(), "foo");
3087     }
3088
3089     #[test]
3090     fn read_link() {
3091         if cfg!(windows) {
3092             // directory symlink
3093             assert_eq!(
3094                 check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
3095                 r"C:\ProgramData"
3096             );
3097             // junction
3098             assert_eq!(
3099                 check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
3100                 r"C:\Users\Default"
3101             );
3102             // junction with special permissions
3103             assert_eq!(
3104                 check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
3105                 r"C:\Users"
3106             );
3107         }
3108         let tmpdir = tmpdir();
3109         let link = tmpdir.join("link");
3110         if !got_symlink_permission(&tmpdir) {
3111             return;
3112         };
3113         check!(symlink_file(&"foo", &link));
3114         assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
3115     }
3116
3117     #[test]
3118     fn readlink_not_symlink() {
3119         let tmpdir = tmpdir();
3120         match fs::read_link(tmpdir.path()) {
3121             Ok(..) => panic!("wanted a failure"),
3122             Err(..) => {}
3123         }
3124     }
3125
3126     #[test]
3127     fn links_work() {
3128         let tmpdir = tmpdir();
3129         let input = tmpdir.join("in.txt");
3130         let out = tmpdir.join("out.txt");
3131
3132         check!(check!(File::create(&input)).write("foobar".as_bytes()));
3133         check!(fs::hard_link(&input, &out));
3134         assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len());
3135         assert_eq!(check!(fs::metadata(&out)).len(), check!(input.metadata()).len());
3136         let mut v = Vec::new();
3137         check!(check!(File::open(&out)).read_to_end(&mut v));
3138         assert_eq!(v, b"foobar".to_vec());
3139
3140         // can't link to yourself
3141         match fs::hard_link(&input, &input) {
3142             Ok(..) => panic!("wanted a failure"),
3143             Err(..) => {}
3144         }
3145         // can't link to something that doesn't exist
3146         match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
3147             Ok(..) => panic!("wanted a failure"),
3148             Err(..) => {}
3149         }
3150     }
3151
3152     #[test]
3153     fn chmod_works() {
3154         let tmpdir = tmpdir();
3155         let file = tmpdir.join("in.txt");
3156
3157         check!(File::create(&file));
3158         let attr = check!(fs::metadata(&file));
3159         assert!(!attr.permissions().readonly());
3160         let mut p = attr.permissions();
3161         p.set_readonly(true);
3162         check!(fs::set_permissions(&file, p.clone()));
3163         let attr = check!(fs::metadata(&file));
3164         assert!(attr.permissions().readonly());
3165
3166         match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
3167             Ok(..) => panic!("wanted an error"),
3168             Err(..) => {}
3169         }
3170
3171         p.set_readonly(false);
3172         check!(fs::set_permissions(&file, p));
3173     }
3174
3175     #[test]
3176     fn fchmod_works() {
3177         let tmpdir = tmpdir();
3178         let path = tmpdir.join("in.txt");
3179
3180         let file = check!(File::create(&path));
3181         let attr = check!(fs::metadata(&path));
3182         assert!(!attr.permissions().readonly());
3183         let mut p = attr.permissions();
3184         p.set_readonly(true);
3185         check!(file.set_permissions(p.clone()));
3186         let attr = check!(fs::metadata(&path));
3187         assert!(attr.permissions().readonly());
3188
3189         p.set_readonly(false);
3190         check!(file.set_permissions(p));
3191     }
3192
3193     #[test]
3194     fn sync_doesnt_kill_anything() {
3195         let tmpdir = tmpdir();
3196         let path = tmpdir.join("in.txt");
3197
3198         let mut file = check!(File::create(&path));
3199         check!(file.sync_all());
3200         check!(file.sync_data());
3201         check!(file.write(b"foo"));
3202         check!(file.sync_all());
3203         check!(file.sync_data());
3204     }
3205
3206     #[test]
3207     fn truncate_works() {
3208         let tmpdir = tmpdir();
3209         let path = tmpdir.join("in.txt");
3210
3211         let mut file = check!(File::create(&path));
3212         check!(file.write(b"foo"));
3213         check!(file.sync_all());
3214
3215         // Do some simple things with truncation
3216         assert_eq!(check!(file.metadata()).len(), 3);
3217         check!(file.set_len(10));
3218         assert_eq!(check!(file.metadata()).len(), 10);
3219         check!(file.write(b"bar"));
3220         check!(file.sync_all());
3221         assert_eq!(check!(file.metadata()).len(), 10);
3222
3223         let mut v = Vec::new();
3224         check!(check!(File::open(&path)).read_to_end(&mut v));
3225         assert_eq!(v, b"foobar\0\0\0\0".to_vec());
3226
3227         // Truncate to a smaller length, don't seek, and then write something.
3228         // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
3229         // past the end of the file).
3230         check!(file.set_len(2));
3231         assert_eq!(check!(file.metadata()).len(), 2);
3232         check!(file.write(b"wut"));
3233         check!(file.sync_all());
3234         assert_eq!(check!(file.metadata()).len(), 9);
3235         let mut v = Vec::new();
3236         check!(check!(File::open(&path)).read_to_end(&mut v));
3237         assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
3238     }
3239
3240     #[test]
3241     fn open_flavors() {
3242         use crate::fs::OpenOptions as OO;
3243         fn c<T: Clone>(t: &T) -> T {
3244             t.clone()
3245         }
3246
3247         let tmpdir = tmpdir();
3248
3249         let mut r = OO::new();
3250         r.read(true);
3251         let mut w = OO::new();
3252         w.write(true);
3253         let mut rw = OO::new();
3254         rw.read(true).write(true);
3255         let mut a = OO::new();
3256         a.append(true);
3257         let mut ra = OO::new();
3258         ra.read(true).append(true);
3259
3260         #[cfg(windows)]
3261         let invalid_options = 87; // ERROR_INVALID_PARAMETER
3262         #[cfg(all(unix, not(target_os = "vxworks")))]
3263         let invalid_options = "Invalid argument";
3264         #[cfg(target_os = "vxworks")]
3265         let invalid_options = "invalid argument";
3266
3267         // Test various combinations of creation modes and access modes.
3268         //
3269         // Allowed:
3270         // creation mode           | read  | write | read-write | append | read-append |
3271         // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
3272         // not set (open existing) |   X   |   X   |     X      |   X    |      X      |
3273         // create                  |       |   X   |     X      |   X    |      X      |
3274         // truncate                |       |   X   |     X      |        |             |
3275         // create and truncate     |       |   X   |     X      |        |             |
3276         // create_new              |       |   X   |     X      |   X    |      X      |
3277         //
3278         // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
3279
3280         // write-only
3281         check!(c(&w).create_new(true).open(&tmpdir.join("a")));
3282         check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
3283         check!(c(&w).truncate(true).open(&tmpdir.join("a")));
3284         check!(c(&w).create(true).open(&tmpdir.join("a")));
3285         check!(c(&w).open(&tmpdir.join("a")));
3286
3287         // read-only
3288         error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
3289         error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
3290         error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
3291         error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
3292         check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
3293
3294         // read-write
3295         check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
3296         check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
3297         check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
3298         check!(c(&rw).create(true).open(&tmpdir.join("c")));
3299         check!(c(&rw).open(&tmpdir.join("c")));
3300
3301         // append
3302         check!(c(&a).create_new(true).open(&tmpdir.join("d")));
3303         error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
3304         error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
3305         check!(c(&a).create(true).open(&tmpdir.join("d")));
3306         check!(c(&a).open(&tmpdir.join("d")));
3307
3308         // read-append
3309         check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
3310         error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
3311         error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
3312         check!(c(&ra).create(true).open(&tmpdir.join("e")));
3313         check!(c(&ra).open(&tmpdir.join("e")));
3314
3315         // Test opening a file without setting an access mode
3316         let mut blank = OO::new();
3317         error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
3318
3319         // Test write works
3320         check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
3321
3322         // Test write fails for read-only
3323         check!(r.open(&tmpdir.join("h")));
3324         {
3325             let mut f = check!(r.open(&tmpdir.join("h")));
3326             assert!(f.write("wut".as_bytes()).is_err());
3327         }
3328
3329         // Test write overwrites
3330         {
3331             let mut f = check!(c(&w).open(&tmpdir.join("h")));
3332             check!(f.write("baz".as_bytes()));
3333         }
3334         {
3335             let mut f = check!(c(&r).open(&tmpdir.join("h")));
3336             let mut b = vec![0; 6];
3337             check!(f.read(&mut b));
3338             assert_eq!(b, "bazbar".as_bytes());
3339         }
3340
3341         // Test truncate works
3342         {
3343             let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
3344             check!(f.write("foo".as_bytes()));
3345         }
3346         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3347
3348         // Test append works
3349         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3350         {
3351             let mut f = check!(c(&a).open(&tmpdir.join("h")));
3352             check!(f.write("bar".as_bytes()));
3353         }
3354         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
3355
3356         // Test .append(true) equals .write(true).append(true)
3357         {
3358             let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
3359             check!(f.write("baz".as_bytes()));
3360         }
3361         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
3362     }
3363
3364     #[test]
3365     fn _assert_send_sync() {
3366         fn _assert_send_sync<T: Send + Sync>() {}
3367         _assert_send_sync::<OpenOptions>();
3368     }
3369
3370     #[test]
3371     fn binary_file() {
3372         let mut bytes = [0; 1024];
3373         StdRng::from_entropy().fill_bytes(&mut bytes);
3374
3375         let tmpdir = tmpdir();
3376
3377         check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
3378         let mut v = Vec::new();
3379         check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
3380         assert!(v == &bytes[..]);
3381     }
3382
3383     #[test]
3384     fn write_then_read() {
3385         let mut bytes = [0; 1024];
3386         StdRng::from_entropy().fill_bytes(&mut bytes);
3387
3388         let tmpdir = tmpdir();
3389
3390         check!(fs::write(&tmpdir.join("test"), &bytes[..]));
3391         let v = check!(fs::read(&tmpdir.join("test")));
3392         assert!(v == &bytes[..]);
3393
3394         check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF]));
3395         error_contains!(
3396             fs::read_to_string(&tmpdir.join("not-utf8")),
3397             "stream did not contain valid UTF-8"
3398         );
3399
3400         let s = "𐁁𐀓𐀠𐀴𐀍";
3401         check!(fs::write(&tmpdir.join("utf8"), s.as_bytes()));
3402         let string = check!(fs::read_to_string(&tmpdir.join("utf8")));
3403         assert_eq!(string, s);
3404     }
3405
3406     #[test]
3407     fn file_try_clone() {
3408         let tmpdir = tmpdir();
3409
3410         let mut f1 = check!(
3411             OpenOptions::new().read(true).write(true).create(true).open(&tmpdir.join("test"))
3412         );
3413         let mut f2 = check!(f1.try_clone());
3414
3415         check!(f1.write_all(b"hello world"));
3416         check!(f1.seek(SeekFrom::Start(2)));
3417
3418         let mut buf = vec![];
3419         check!(f2.read_to_end(&mut buf));
3420         assert_eq!(buf, b"llo world");
3421         drop(f2);
3422
3423         check!(f1.write_all(b"!"));
3424     }
3425
3426     #[test]
3427     #[cfg(not(windows))]
3428     fn unlink_readonly() {
3429         let tmpdir = tmpdir();
3430         let path = tmpdir.join("file");
3431         check!(File::create(&path));
3432         let mut perm = check!(fs::metadata(&path)).permissions();
3433         perm.set_readonly(true);
3434         check!(fs::set_permissions(&path, perm));
3435         check!(fs::remove_file(&path));
3436     }
3437
3438     #[test]
3439     fn mkdir_trailing_slash() {
3440         let tmpdir = tmpdir();
3441         let path = tmpdir.join("file");
3442         check!(fs::create_dir_all(&path.join("a/")));
3443     }
3444
3445     #[test]
3446     fn canonicalize_works_simple() {
3447         let tmpdir = tmpdir();
3448         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3449         let file = tmpdir.join("test");
3450         File::create(&file).unwrap();
3451         assert_eq!(fs::canonicalize(&file).unwrap(), file);
3452     }
3453
3454     #[test]
3455     fn realpath_works() {
3456         let tmpdir = tmpdir();
3457         if !got_symlink_permission(&tmpdir) {
3458             return;
3459         };
3460
3461         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3462         let file = tmpdir.join("test");
3463         let dir = tmpdir.join("test2");
3464         let link = dir.join("link");
3465         let linkdir = tmpdir.join("test3");
3466
3467         File::create(&file).unwrap();
3468         fs::create_dir(&dir).unwrap();
3469         symlink_file(&file, &link).unwrap();
3470         symlink_dir(&dir, &linkdir).unwrap();
3471
3472         assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
3473
3474         assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
3475         assert_eq!(fs::canonicalize(&file).unwrap(), file);
3476         assert_eq!(fs::canonicalize(&link).unwrap(), file);
3477         assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
3478         assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
3479     }
3480
3481     #[test]
3482     fn realpath_works_tricky() {
3483         let tmpdir = tmpdir();
3484         if !got_symlink_permission(&tmpdir) {
3485             return;
3486         };
3487
3488         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3489         let a = tmpdir.join("a");
3490         let b = a.join("b");
3491         let c = b.join("c");
3492         let d = a.join("d");
3493         let e = d.join("e");
3494         let f = a.join("f");
3495
3496         fs::create_dir_all(&b).unwrap();
3497         fs::create_dir_all(&d).unwrap();
3498         File::create(&f).unwrap();
3499         if cfg!(not(windows)) {
3500             symlink_file("../d/e", &c).unwrap();
3501             symlink_file("../f", &e).unwrap();
3502         }
3503         if cfg!(windows) {
3504             symlink_file(r"..\d\e", &c).unwrap();
3505             symlink_file(r"..\f", &e).unwrap();
3506         }
3507
3508         assert_eq!(fs::canonicalize(&c).unwrap(), f);
3509         assert_eq!(fs::canonicalize(&e).unwrap(), f);
3510     }
3511
3512     #[test]
3513     fn dir_entry_methods() {
3514         let tmpdir = tmpdir();
3515
3516         fs::create_dir_all(&tmpdir.join("a")).unwrap();
3517         File::create(&tmpdir.join("b")).unwrap();
3518
3519         for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
3520             let fname = file.file_name();
3521             match fname.to_str() {
3522                 Some("a") => {
3523                     assert!(file.file_type().unwrap().is_dir());
3524                     assert!(file.metadata().unwrap().is_dir());
3525                 }
3526                 Some("b") => {
3527                     assert!(file.file_type().unwrap().is_file());
3528                     assert!(file.metadata().unwrap().is_file());
3529                 }
3530                 f => panic!("unknown file name: {:?}", f),
3531             }
3532         }
3533     }
3534
3535     #[test]
3536     fn dir_entry_debug() {
3537         let tmpdir = tmpdir();
3538         File::create(&tmpdir.join("b")).unwrap();
3539         let mut read_dir = tmpdir.path().read_dir().unwrap();
3540         let dir_entry = read_dir.next().unwrap().unwrap();
3541         let actual = format!("{:?}", dir_entry);
3542         let expected = format!("DirEntry({:?})", dir_entry.0.path());
3543         assert_eq!(actual, expected);
3544     }
3545
3546     #[test]
3547     fn read_dir_not_found() {
3548         let res = fs::read_dir("/path/that/does/not/exist");
3549         assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
3550     }
3551
3552     #[test]
3553     fn create_dir_all_with_junctions() {
3554         let tmpdir = tmpdir();
3555         let target = tmpdir.join("target");
3556
3557         let junction = tmpdir.join("junction");
3558         let b = junction.join("a/b");
3559
3560         let link = tmpdir.join("link");
3561         let d = link.join("c/d");
3562
3563         fs::create_dir(&target).unwrap();
3564
3565         check!(symlink_junction(&target, &junction));
3566         check!(fs::create_dir_all(&b));
3567         // the junction itself is not a directory, but `is_dir()` on a Path
3568         // follows links
3569         assert!(junction.is_dir());
3570         assert!(b.exists());
3571
3572         if !got_symlink_permission(&tmpdir) {
3573             return;
3574         };
3575         check!(symlink_dir(&target, &link));
3576         check!(fs::create_dir_all(&d));
3577         assert!(link.is_dir());
3578         assert!(d.exists());
3579     }
3580
3581     #[test]
3582     fn metadata_access_times() {
3583         let tmpdir = tmpdir();
3584
3585         let b = tmpdir.join("b");
3586         File::create(&b).unwrap();
3587
3588         let a = check!(fs::metadata(&tmpdir.path()));
3589         let b = check!(fs::metadata(&b));
3590
3591         assert_eq!(check!(a.accessed()), check!(a.accessed()));
3592         assert_eq!(check!(a.modified()), check!(a.modified()));
3593         assert_eq!(check!(b.accessed()), check!(b.modified()));
3594
3595         if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3596             check!(a.created());
3597             check!(b.created());
3598         }
3599
3600         if cfg!(target_os = "linux") {
3601             // Not always available
3602             match (a.created(), b.created()) {
3603                 (Ok(t1), Ok(t2)) => assert!(t1 <= t2),
3604                 (Err(e1), Err(e2))
3605                     if e1.kind() == ErrorKind::Other && e2.kind() == ErrorKind::Other => {}
3606                 (a, b) => panic!(
3607                     "creation time must be always supported or not supported: {:?} {:?}",
3608                     a, b,
3609                 ),
3610             }
3611         }
3612     }
3613 }