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