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