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