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