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