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