]> git.lizzy.rs Git - rust.git/blob - src/libstd/fs.rs
Rollup merge of #25614 - parir:patch-2, r=alexcrichton
[rust.git] / src / libstd / fs.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Filesystem manipulation operations
12 //!
13 //! This module contains basic methods to manipulate the contents of the local
14 //! filesystem. All methods in this module represent cross-platform filesystem
15 //! operations. Extra platform-specific functionality can be found in the
16 //! extension traits of `std::os::$platform`.
17
18 #![stable(feature = "rust1", since = "1.0.0")]
19
20 use core::prelude::*;
21
22 use fmt;
23 use ffi::OsString;
24 use io::{self, Error, ErrorKind, SeekFrom, Seek, Read, Write};
25 use path::{Path, PathBuf};
26 use sys::fs as fs_imp;
27 use sys_common::{AsInnerMut, FromInner, AsInner};
28 use vec::Vec;
29
30 /// A reference to an open file on the filesystem.
31 ///
32 /// An instance of a `File` can be read and/or written depending on what options
33 /// it was opened with. Files also implement `Seek` to alter the logical cursor
34 /// that the file contains internally.
35 ///
36 /// # Examples
37 ///
38 /// ```no_run
39 /// use std::io::prelude::*;
40 /// use std::fs::File;
41 ///
42 /// # fn foo() -> std::io::Result<()> {
43 /// let mut f = try!(File::create("foo.txt"));
44 /// try!(f.write_all(b"Hello, world!"));
45 ///
46 /// let mut f = try!(File::open("foo.txt"));
47 /// let mut s = String::new();
48 /// try!(f.read_to_string(&mut s));
49 /// assert_eq!(s, "Hello, world!");
50 /// # Ok(())
51 /// # }
52 /// ```
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub struct File {
55     inner: fs_imp::File,
56 }
57
58 /// Metadata information about a file.
59 ///
60 /// This structure is returned from the `metadata` function or method and
61 /// represents known metadata about a file such as its permissions, size,
62 /// modification times, etc.
63 #[stable(feature = "rust1", since = "1.0.0")]
64 pub struct Metadata(fs_imp::FileAttr);
65
66 /// Iterator over the entries in a directory.
67 ///
68 /// This iterator is returned from the `read_dir` function of this module and
69 /// will yield instances of `io::Result<DirEntry>`. Through a `DirEntry`
70 /// information like the entry's path and possibly other metadata can be
71 /// learned.
72 ///
73 /// # Failure
74 ///
75 /// This `io::Result` will be an `Err` if there's some sort of intermittent
76 /// IO error during iteration.
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub struct ReadDir(fs_imp::ReadDir);
79
80 /// Entries returned by the `ReadDir` iterator.
81 ///
82 /// An instance of `DirEntry` represents an entry inside of a directory on the
83 /// filesystem. Each entry can be inspected via methods to learn about the full
84 /// path or possibly other metadata through per-platform extension traits.
85 #[stable(feature = "rust1", since = "1.0.0")]
86 pub struct DirEntry(fs_imp::DirEntry);
87
88 /// An iterator that recursively walks over the contents of a directory.
89 #[unstable(feature = "fs_walk",
90            reason = "the precise semantics and defaults for a recursive walk \
91                      may change and this may end up accounting for files such \
92                      as symlinks differently")]
93 pub struct WalkDir {
94     cur: Option<ReadDir>,
95     stack: Vec<io::Result<ReadDir>>,
96 }
97
98 /// Options and flags which can be used to configure how a file is opened.
99 ///
100 /// This builder exposes the ability to configure how a `File` is opened and
101 /// what operations are permitted on the open file. The `File::open` and
102 /// `File::create` methods are aliases for commonly used options using this
103 /// builder.
104 ///
105 /// Generally speaking, when using `OpenOptions`, you'll first call `new()`,
106 /// then chain calls to methods to set each option, then call `open()`, passing
107 /// the path of the file you're trying to open. This will give you a
108 /// [`io::Result`][result] with a [`File`][file] inside that you can further
109 /// operate on.
110 ///
111 /// [result]: ../io/type.Result.html
112 /// [file]: struct.File.html
113 ///
114 /// # Examples
115 ///
116 /// Opening a file to read:
117 ///
118 /// ```no_run
119 /// use std::fs::OpenOptions;
120 ///
121 /// let file = OpenOptions::new().read(true).open("foo.txt");
122 /// ```
123 ///
124 /// Opening a file for both reading and writing, as well as creating it if it
125 /// doesn't exist:
126 ///
127 /// ```no_run
128 /// use std::fs::OpenOptions;
129 ///
130 /// let file = OpenOptions::new()
131 ///             .read(true)
132 ///             .write(true)
133 ///             .create(true)
134 ///             .open("foo.txt");
135 /// ```
136 #[derive(Clone)]
137 #[stable(feature = "rust1", since = "1.0.0")]
138 pub struct OpenOptions(fs_imp::OpenOptions);
139
140 /// Representation of the various permissions on a file.
141 ///
142 /// This module only currently provides one bit of information, `readonly`,
143 /// which is exposed on all currently supported platforms. Unix-specific
144 /// functionality, such as mode bits, is available through the
145 /// `os::unix::PermissionsExt` trait.
146 #[derive(Clone, PartialEq, Eq, Debug)]
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub struct Permissions(fs_imp::FilePermissions);
149
150 /// An structure representing a type of file with accessors for each file type.
151 #[unstable(feature = "file_type", reason = "recently added API")]
152 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
153 pub struct FileType(fs_imp::FileType);
154
155 /// A builder used to create directories in various manners.
156 ///
157 /// This builder also supports platform-specific options.
158 #[unstable(feature = "dir_builder", reason = "recently added API")]
159 pub struct DirBuilder {
160     inner: fs_imp::DirBuilder,
161     recursive: bool,
162 }
163
164 impl File {
165     /// Attempts to open a file in read-only mode.
166     ///
167     /// See the `OpenOptions::open` method for more details.
168     ///
169     /// # Errors
170     ///
171     /// This function will return an error if `path` does not already exist.
172     /// Other errors may also be returned according to `OpenOptions::open`.
173     ///
174     /// # Examples
175     ///
176     /// ```no_run
177     /// use std::fs::File;
178     ///
179     /// # fn foo() -> std::io::Result<()> {
180     /// let mut f = try!(File::open("foo.txt"));
181     /// # Ok(())
182     /// # }
183     /// ```
184     #[stable(feature = "rust1", since = "1.0.0")]
185     pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
186         OpenOptions::new().read(true).open(path)
187     }
188
189     /// Opens a file in write-only mode.
190     ///
191     /// This function will create a file if it does not exist,
192     /// and will truncate it if it does.
193     ///
194     /// See the `OpenOptions::open` function for more details.
195     ///
196     /// # Examples
197     ///
198     /// ```no_run
199     /// use std::fs::File;
200     ///
201     /// # fn foo() -> std::io::Result<()> {
202     /// let mut f = try!(File::create("foo.txt"));
203     /// # Ok(())
204     /// # }
205     /// ```
206     #[stable(feature = "rust1", since = "1.0.0")]
207     pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
208         OpenOptions::new().write(true).create(true).truncate(true).open(path)
209     }
210
211     /// Returns `None`.
212     #[unstable(feature = "file_path",
213                reason = "this abstraction was imposed by this library and was removed")]
214     #[deprecated(since = "1.0.0", reason = "abstraction was removed")]
215     pub fn path(&self) -> Option<&Path> {
216         None
217     }
218
219     /// Attempts to sync all OS-internal metadata to disk.
220     ///
221     /// This function will attempt to ensure that all in-core data reaches the
222     /// filesystem before returning.
223     ///
224     /// # Examples
225     ///
226     /// ```no_run
227     /// use std::fs::File;
228     /// use std::io::prelude::*;
229     ///
230     /// # fn foo() -> std::io::Result<()> {
231     /// let mut f = try!(File::create("foo.txt"));
232     /// try!(f.write_all(b"Hello, world!"));
233     ///
234     /// try!(f.sync_all());
235     /// # Ok(())
236     /// # }
237     /// ```
238     #[stable(feature = "rust1", since = "1.0.0")]
239     pub fn sync_all(&self) -> io::Result<()> {
240         self.inner.fsync()
241     }
242
243     /// This function is similar to `sync_all`, except that it may not
244     /// synchronize file metadata to the filesystem.
245     ///
246     /// This is intended for use cases that must synchronize content, but don't
247     /// need the metadata on disk. The goal of this method is to reduce disk
248     /// operations.
249     ///
250     /// Note that some platforms may simply implement this in terms of
251     /// `sync_all`.
252     ///
253     /// # Examples
254     ///
255     /// ```no_run
256     /// use std::fs::File;
257     /// use std::io::prelude::*;
258     ///
259     /// # fn foo() -> std::io::Result<()> {
260     /// let mut f = try!(File::create("foo.txt"));
261     /// try!(f.write_all(b"Hello, world!"));
262     ///
263     /// try!(f.sync_data());
264     /// # Ok(())
265     /// # }
266     /// ```
267     #[stable(feature = "rust1", since = "1.0.0")]
268     pub fn sync_data(&self) -> io::Result<()> {
269         self.inner.datasync()
270     }
271
272     /// Truncates or extends the underlying file, updating the size of
273     /// this file to become `size`.
274     ///
275     /// If the `size` is less than the current file's size, then the file will
276     /// be shrunk. If it is greater than the current file's size, then the file
277     /// will be extended to `size` and have all of the intermediate data filled
278     /// in with 0s.
279     ///
280     /// # Examples
281     ///
282     /// ```no_run
283     /// use std::fs::File;
284     ///
285     /// # fn foo() -> std::io::Result<()> {
286     /// let mut f = try!(File::open("foo.txt"));
287     /// try!(f.set_len(0));
288     /// # Ok(())
289     /// # }
290     /// ```
291     #[stable(feature = "rust1", since = "1.0.0")]
292     pub fn set_len(&self, size: u64) -> io::Result<()> {
293         self.inner.truncate(size)
294     }
295
296     /// Queries metadata about the underlying file.
297     ///
298     /// # Examples
299     ///
300     /// ```no_run
301     /// use std::fs::File;
302     ///
303     /// # fn foo() -> std::io::Result<()> {
304     /// let mut f = try!(File::open("foo.txt"));
305     /// let metadata = try!(f.metadata());
306     /// # Ok(())
307     /// # }
308     /// ```
309     #[stable(feature = "rust1", since = "1.0.0")]
310     pub fn metadata(&self) -> io::Result<Metadata> {
311         self.inner.file_attr().map(Metadata)
312     }
313 }
314
315 impl AsInner<fs_imp::File> for File {
316     fn as_inner(&self) -> &fs_imp::File { &self.inner }
317 }
318 impl FromInner<fs_imp::File> for File {
319     fn from_inner(f: fs_imp::File) -> File {
320         File { inner: f }
321     }
322 }
323
324 impl fmt::Debug for File {
325     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
326         self.inner.fmt(f)
327     }
328 }
329
330 #[stable(feature = "rust1", since = "1.0.0")]
331 impl Read for File {
332     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
333         self.inner.read(buf)
334     }
335 }
336 #[stable(feature = "rust1", since = "1.0.0")]
337 impl Write for File {
338     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
339         self.inner.write(buf)
340     }
341     fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
342 }
343 #[stable(feature = "rust1", since = "1.0.0")]
344 impl Seek for File {
345     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
346         self.inner.seek(pos)
347     }
348 }
349 #[stable(feature = "rust1", since = "1.0.0")]
350 impl<'a> Read for &'a File {
351     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
352         self.inner.read(buf)
353     }
354 }
355 #[stable(feature = "rust1", since = "1.0.0")]
356 impl<'a> Write for &'a File {
357     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
358         self.inner.write(buf)
359     }
360     fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
361 }
362 #[stable(feature = "rust1", since = "1.0.0")]
363 impl<'a> Seek for &'a File {
364     fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
365         self.inner.seek(pos)
366     }
367 }
368
369 impl OpenOptions {
370     /// Creates a blank net set of options ready for configuration.
371     ///
372     /// All options are initially set to `false`.
373     ///
374     /// # Examples
375     ///
376     /// ```no_run
377     /// use std::fs::OpenOptions;
378     ///
379     /// let file = OpenOptions::new().open("foo.txt");
380     /// ```
381     #[stable(feature = "rust1", since = "1.0.0")]
382     pub fn new() -> OpenOptions {
383         OpenOptions(fs_imp::OpenOptions::new())
384     }
385
386     /// Sets the option for read access.
387     ///
388     /// This option, when true, will indicate that the file should be
389     /// `read`-able if opened.
390     ///
391     /// # Examples
392     ///
393     /// ```no_run
394     /// use std::fs::OpenOptions;
395     ///
396     /// let file = OpenOptions::new().read(true).open("foo.txt");
397     /// ```
398     #[stable(feature = "rust1", since = "1.0.0")]
399     pub fn read(&mut self, read: bool) -> &mut OpenOptions {
400         self.0.read(read); self
401     }
402
403     /// Sets the option for write access.
404     ///
405     /// This option, when true, will indicate that the file should be
406     /// `write`-able if opened.
407     ///
408     /// # Examples
409     ///
410     /// ```no_run
411     /// use std::fs::OpenOptions;
412     ///
413     /// let file = OpenOptions::new().write(true).open("foo.txt");
414     /// ```
415     #[stable(feature = "rust1", since = "1.0.0")]
416     pub fn write(&mut self, write: bool) -> &mut OpenOptions {
417         self.0.write(write); self
418     }
419
420     /// Sets the option for the append mode.
421     ///
422     /// This option, when true, means that writes will append to a file instead
423     /// of overwriting previous contents.
424     ///
425     /// # Examples
426     ///
427     /// ```no_run
428     /// use std::fs::OpenOptions;
429     ///
430     /// let file = OpenOptions::new().append(true).open("foo.txt");
431     /// ```
432     #[stable(feature = "rust1", since = "1.0.0")]
433     pub fn append(&mut self, append: bool) -> &mut OpenOptions {
434         self.0.append(append); self
435     }
436
437     /// Sets the option for truncating a previous file.
438     ///
439     /// If a file is successfully opened with this option set it will truncate
440     /// the file to 0 length if it already exists.
441     ///
442     /// # Examples
443     ///
444     /// ```no_run
445     /// use std::fs::OpenOptions;
446     ///
447     /// let file = OpenOptions::new().truncate(true).open("foo.txt");
448     /// ```
449     #[stable(feature = "rust1", since = "1.0.0")]
450     pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
451         self.0.truncate(truncate); self
452     }
453
454     /// Sets the option for creating a new file.
455     ///
456     /// This option indicates whether a new file will be created if the file
457     /// does not yet already exist.
458     ///
459     /// # Examples
460     ///
461     /// ```no_run
462     /// use std::fs::OpenOptions;
463     ///
464     /// let file = OpenOptions::new().create(true).open("foo.txt");
465     /// ```
466     #[stable(feature = "rust1", since = "1.0.0")]
467     pub fn create(&mut self, create: bool) -> &mut OpenOptions {
468         self.0.create(create); self
469     }
470
471     /// Opens a file at `path` with the options specified by `self`.
472     ///
473     /// # Errors
474     ///
475     /// This function will return an error under a number of different
476     /// circumstances, to include but not limited to:
477     ///
478     /// * Opening a file that does not exist with read access.
479     /// * Attempting to open a file with access that the user lacks
480     ///   permissions for
481     /// * Filesystem-level errors (full disk, etc)
482     ///
483     /// # Examples
484     ///
485     /// ```no_run
486     /// use std::fs::OpenOptions;
487     ///
488     /// let file = OpenOptions::new().open("foo.txt");
489     /// ```
490     #[stable(feature = "rust1", since = "1.0.0")]
491     pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
492         let path = path.as_ref();
493         let inner = try!(fs_imp::File::open(path, &self.0));
494         Ok(File { inner: inner })
495     }
496 }
497
498 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
499     fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
500 }
501
502 impl Metadata {
503     /// Returns the file type for this metadata.
504     #[unstable(feature = "file_type", reason = "recently added API")]
505     pub fn file_type(&self) -> FileType {
506         FileType(self.0.file_type())
507     }
508
509     /// Returns whether this metadata is for a directory.
510     ///
511     /// # Examples
512     ///
513     /// ```
514     /// # fn foo() -> std::io::Result<()> {
515     /// use std::fs;
516     ///
517     /// let metadata = try!(fs::metadata("foo.txt"));
518     ///
519     /// assert!(!metadata.is_dir());
520     /// # Ok(())
521     /// # }
522     /// ```
523     #[stable(feature = "rust1", since = "1.0.0")]
524     pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
525
526     /// Returns whether this metadata is for a regular file.
527     ///
528     /// # Examples
529     ///
530     /// ```
531     /// # fn foo() -> std::io::Result<()> {
532     /// use std::fs;
533     ///
534     /// let metadata = try!(fs::metadata("foo.txt"));
535     ///
536     /// assert!(metadata.is_file());
537     /// # Ok(())
538     /// # }
539     /// ```
540     #[stable(feature = "rust1", since = "1.0.0")]
541     pub fn is_file(&self) -> bool { self.file_type().is_file() }
542
543     /// Returns the size of the file, in bytes, this metadata is for.
544     ///
545     /// # Examples
546     ///
547     /// ```
548     /// # fn foo() -> std::io::Result<()> {
549     /// use std::fs;
550     ///
551     /// let metadata = try!(fs::metadata("foo.txt"));
552     ///
553     /// assert_eq!(0, metadata.len());
554     /// # Ok(())
555     /// # }
556     /// ```
557     #[stable(feature = "rust1", since = "1.0.0")]
558     pub fn len(&self) -> u64 { self.0.size() }
559
560     /// Returns the permissions of the file this metadata is for.
561     ///
562     /// # Examples
563     ///
564     /// ```
565     /// # fn foo() -> std::io::Result<()> {
566     /// use std::fs;
567     ///
568     /// let metadata = try!(fs::metadata("foo.txt"));
569     ///
570     /// assert!(!metadata.permissions().readonly());
571     /// # Ok(())
572     /// # }
573     /// ```
574     #[stable(feature = "rust1", since = "1.0.0")]
575     pub fn permissions(&self) -> Permissions {
576         Permissions(self.0.perm())
577     }
578
579     /// Returns the most recent access time for a file.
580     ///
581     /// The return value is in milliseconds since the epoch.
582     #[unstable(feature = "fs_time",
583                reason = "the return type of u64 is not quite appropriate for \
584                          this method and may change if the standard library \
585                          gains a type to represent a moment in time")]
586     #[deprecated(since = "1.1.0",
587                  reason = "use os::platform::fs::MetadataExt extension traits")]
588     pub fn accessed(&self) -> u64 {
589         self.adjust_time(self.0.accessed())
590     }
591
592     /// Returns the most recent modification time for a file.
593     ///
594     /// The return value is in milliseconds since the epoch.
595     #[unstable(feature = "fs_time",
596                reason = "the return type of u64 is not quite appropriate for \
597                          this method and may change if the standard library \
598                          gains a type to represent a moment in time")]
599     #[deprecated(since = "1.1.0",
600                  reason = "use os::platform::fs::MetadataExt extension traits")]
601     pub fn modified(&self) -> u64 {
602         self.adjust_time(self.0.modified())
603     }
604
605     fn adjust_time(&self, val: u64) -> u64 {
606         // FILETIME (what `val` represents) is in 100ns intervals and there are
607         // 10000 intervals in a millisecond.
608         if cfg!(windows) {val / 10000} else {val}
609     }
610 }
611
612 impl AsInner<fs_imp::FileAttr> for Metadata {
613     fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
614 }
615
616 impl Permissions {
617     /// Returns whether these permissions describe a readonly file.
618     ///
619     /// # Examples
620     ///
621     /// ```
622     /// use std::fs::File;
623     ///
624     /// # fn foo() -> std::io::Result<()> {
625     /// let mut f = try!(File::create("foo.txt"));
626     /// let metadata = try!(f.metadata());
627     ///
628     /// assert_eq!(false, metadata.permissions().readonly());
629     /// # Ok(())
630     /// # }
631     /// ```
632     #[stable(feature = "rust1", since = "1.0.0")]
633     pub fn readonly(&self) -> bool { self.0.readonly() }
634
635     /// Modifies the readonly flag for this set of permissions.
636     ///
637     /// This operation does **not** modify the filesystem. To modify the
638     /// filesystem use the `fs::set_permissions` function.
639     ///
640     /// # Examples
641     ///
642     /// ```
643     /// use std::fs::File;
644     ///
645     /// # fn foo() -> std::io::Result<()> {
646     /// let f = try!(File::create("foo.txt"));
647     /// let metadata = try!(f.metadata());
648     /// let mut permissions = metadata.permissions();
649     ///
650     /// permissions.set_readonly(true);
651     ///
652     /// // filesystem doesn't change
653     /// assert_eq!(false, metadata.permissions().readonly());
654     ///
655     /// // just this particular `permissions`.
656     /// assert_eq!(true, permissions.readonly());
657     /// # Ok(())
658     /// # }
659     /// ```
660     #[stable(feature = "rust1", since = "1.0.0")]
661     pub fn set_readonly(&mut self, readonly: bool) {
662         self.0.set_readonly(readonly)
663     }
664 }
665
666 #[unstable(feature = "file_type", reason = "recently added API")]
667 impl FileType {
668     /// Test whether this file type represents a directory.
669     pub fn is_dir(&self) -> bool { self.0.is_dir() }
670
671     /// Test whether this file type represents a regular file.
672     pub fn is_file(&self) -> bool { self.0.is_file() }
673
674     /// Test whether this file type represents a symbolic link.
675     pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
676 }
677
678 impl FromInner<fs_imp::FilePermissions> for Permissions {
679     fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
680         Permissions(f)
681     }
682 }
683
684 impl AsInner<fs_imp::FilePermissions> for Permissions {
685     fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
686 }
687
688 #[stable(feature = "rust1", since = "1.0.0")]
689 impl Iterator for ReadDir {
690     type Item = io::Result<DirEntry>;
691
692     fn next(&mut self) -> Option<io::Result<DirEntry>> {
693         self.0.next().map(|entry| entry.map(DirEntry))
694     }
695 }
696
697 #[stable(feature = "rust1", since = "1.0.0")]
698 impl DirEntry {
699     /// Returns the full path to the file that this entry represents.
700     ///
701     /// The full path is created by joining the original path to `read_dir` or
702     /// `walk_dir` with the filename of this entry.
703     ///
704     /// # Examples
705     ///
706     /// ```
707     /// use std::fs;
708     /// # fn foo() -> std::io::Result<()> {
709     /// for entry in try!(fs::read_dir(".")) {
710     ///     let dir = try!(entry);
711     ///     println!("{:?}", dir.path());
712     /// }
713     /// # Ok(())
714     /// # }
715     /// ```
716     ///
717     /// This prints output like:
718     ///
719     /// ```text
720     /// "./whatever.txt"
721     /// "./foo.html"
722     /// "./hello_world.rs"
723     /// ```
724     ///
725     /// The exact text, of course, depends on what files you have in `.`.
726     #[stable(feature = "rust1", since = "1.0.0")]
727     pub fn path(&self) -> PathBuf { self.0.path() }
728
729     /// Return the metadata for the file that this entry points at.
730     ///
731     /// This function will not traverse symlinks if this entry points at a
732     /// symlink.
733     ///
734     /// # Platform behavior
735     ///
736     /// On Windows this function is cheap to call (no extra system calls
737     /// needed), but on Unix platforms this function is the equivalent of
738     /// calling `symlink_metadata` on the path.
739     #[unstable(feature = "dir_entry_ext", reason = "recently added API")]
740     pub fn metadata(&self) -> io::Result<Metadata> {
741         self.0.metadata().map(Metadata)
742     }
743
744     /// Return the file type for the file that this entry points at.
745     ///
746     /// This function will not traverse symlinks if this entry points at a
747     /// symlink.
748     ///
749     /// # Platform behavior
750     ///
751     /// On Windows and most Unix platforms this function is free (no extra
752     /// system calls needed), but some Unix platforms may require the equivalent
753     /// call to `symlink_metadata` to learn about the target file type.
754     #[unstable(feature = "dir_entry_ext", reason = "recently added API")]
755     pub fn file_type(&self) -> io::Result<FileType> {
756         self.0.file_type().map(FileType)
757     }
758
759     /// Returns the bare file name of this directory entry without any other
760     /// leading path component.
761     #[unstable(feature = "dir_entry_ext", reason = "recently added API")]
762     pub fn file_name(&self) -> OsString {
763         self.0.file_name()
764     }
765 }
766
767 impl AsInner<fs_imp::DirEntry> for DirEntry {
768     fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
769 }
770
771 /// Removes a file from the underlying filesystem.
772 ///
773 /// Note that, just because an unlink call was successful, it is not
774 /// guaranteed that a file is immediately deleted (e.g. depending on
775 /// platform, other open file descriptors may prevent immediate removal).
776 ///
777 /// # Errors
778 ///
779 /// This function will return an error if `path` points to a directory, if the
780 /// user lacks permissions to remove the file, or if some other filesystem-level
781 /// error occurs.
782 ///
783 /// # Examples
784 ///
785 /// ```
786 /// use std::fs;
787 ///
788 /// # fn foo() -> std::io::Result<()> {
789 /// try!(fs::remove_file("a.txt"));
790 /// # Ok(())
791 /// # }
792 /// ```
793 #[stable(feature = "rust1", since = "1.0.0")]
794 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
795     fs_imp::unlink(path.as_ref())
796 }
797
798 /// Given a path, query the file system to get information about a file,
799 /// directory, etc.
800 ///
801 /// This function will traverse symbolic links to query information about the
802 /// destination file.
803 ///
804 /// # Examples
805 ///
806 /// ```rust
807 /// # fn foo() -> std::io::Result<()> {
808 /// use std::fs;
809 ///
810 /// let attr = try!(fs::metadata("/some/file/path.txt"));
811 /// // inspect attr ...
812 /// # Ok(())
813 /// # }
814 /// ```
815 ///
816 /// # Errors
817 ///
818 /// This function will return an error if the user lacks the requisite
819 /// permissions to perform a `metadata` call on the given `path` or if there
820 /// is no entry in the filesystem at the provided path.
821 #[stable(feature = "rust1", since = "1.0.0")]
822 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
823     fs_imp::stat(path.as_ref()).map(Metadata)
824 }
825
826 /// Query the metadata about a file without following symlinks.
827 ///
828 /// # Examples
829 ///
830 /// ```rust
831 /// #![feature(symlink_metadata)]
832 /// # fn foo() -> std::io::Result<()> {
833 /// use std::fs;
834 ///
835 /// let attr = try!(fs::symlink_metadata("/some/file/path.txt"));
836 /// // inspect attr ...
837 /// # Ok(())
838 /// # }
839 /// ```
840 #[unstable(feature = "symlink_metadata", reason = "recently added API")]
841 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
842     fs_imp::lstat(path.as_ref()).map(Metadata)
843 }
844
845 /// Rename a file or directory to a new name.
846 ///
847 /// # Errors
848 ///
849 /// This function will return an error if the provided `from` doesn't exist, if
850 /// the process lacks permissions to view the contents, if `from` and `to`
851 /// reside on separate filesystems, or if some other intermittent I/O error
852 /// occurs.
853 ///
854 /// # Examples
855 ///
856 /// ```
857 /// use std::fs;
858 ///
859 /// # fn foo() -> std::io::Result<()> {
860 /// try!(fs::rename("a.txt", "b.txt"));
861 /// # Ok(())
862 /// # }
863 /// ```
864 #[stable(feature = "rust1", since = "1.0.0")]
865 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
866     fs_imp::rename(from.as_ref(), to.as_ref())
867 }
868
869 /// Copies the contents of one file to another. This function will also
870 /// copy the permission bits of the original file to the destination file.
871 ///
872 /// This function will **overwrite** the contents of `to`.
873 ///
874 /// Note that if `from` and `to` both point to the same file, then the file
875 /// will likely get truncated by this operation.
876 ///
877 /// # Errors
878 ///
879 /// This function will return an error in the following situations, but is not
880 /// limited to just these cases:
881 ///
882 /// * The `from` path is not a file
883 /// * The `from` file does not exist
884 /// * The current process does not have the permission rights to access
885 ///   `from` or write `to`
886 ///
887 /// # Examples
888 ///
889 /// ```no_run
890 /// use std::fs;
891 ///
892 /// # fn foo() -> std::io::Result<()> {
893 /// try!(fs::copy("foo.txt", "bar.txt"));
894 /// # Ok(()) }
895 /// ```
896 #[stable(feature = "rust1", since = "1.0.0")]
897 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
898     let from = from.as_ref();
899     let to = to.as_ref();
900     if !from.is_file() {
901         return Err(Error::new(ErrorKind::InvalidInput,
902                               "the source path is not an existing file"))
903     }
904
905     let mut reader = try!(File::open(from));
906     let mut writer = try!(File::create(to));
907     let perm = try!(reader.metadata()).permissions();
908
909     let ret = try!(io::copy(&mut reader, &mut writer));
910     try!(set_permissions(to, perm));
911     Ok(ret)
912 }
913
914 /// Creates a new hard link on the filesystem.
915 ///
916 /// The `dst` path will be a link pointing to the `src` path. Note that systems
917 /// often require these two paths to both be located on the same filesystem.
918 ///
919 /// # Examples
920 ///
921 /// ```
922 /// use std::fs;
923 ///
924 /// # fn foo() -> std::io::Result<()> {
925 /// try!(fs::hard_link("a.txt", "b.txt"));
926 /// # Ok(())
927 /// # }
928 /// ```
929 #[stable(feature = "rust1", since = "1.0.0")]
930 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
931     fs_imp::link(src.as_ref(), dst.as_ref())
932 }
933
934 /// Creates a new symbolic link on the filesystem.
935 ///
936 /// The `dst` path will be a symbolic link pointing to the `src` path.
937 /// On Windows, this will be a file symlink, not a directory symlink;
938 /// for this reason, the platform-specific `std::os::unix::fs::symlink`
939 /// and `std::os::windows::fs::{symlink_file, symlink_dir}` should be
940 /// used instead to make the intent explicit.
941 ///
942 /// # Examples
943 ///
944 /// ```
945 /// use std::fs;
946 ///
947 /// # fn foo() -> std::io::Result<()> {
948 /// try!(fs::soft_link("a.txt", "b.txt"));
949 /// # Ok(())
950 /// # }
951 /// ```
952 #[deprecated(since = "1.0.0",
953              reason = "replaced with std::os::unix::fs::symlink and \
954                        std::os::windows::fs::{symlink_file, symlink_dir}")]
955 #[stable(feature = "rust1", since = "1.0.0")]
956 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
957     fs_imp::symlink(src.as_ref(), dst.as_ref())
958 }
959
960 /// Reads a symbolic link, returning the file that the link points to.
961 ///
962 /// # Errors
963 ///
964 /// This function will return an error on failure. Failure conditions include
965 /// reading a file that does not exist or reading a file that is not a symbolic
966 /// link.
967 ///
968 /// # Examples
969 ///
970 /// ```
971 /// use std::fs;
972 ///
973 /// # fn foo() -> std::io::Result<()> {
974 /// let path = try!(fs::read_link("a.txt"));
975 /// # Ok(())
976 /// # }
977 /// ```
978 #[stable(feature = "rust1", since = "1.0.0")]
979 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
980     fs_imp::readlink(path.as_ref())
981 }
982
983 /// Returns the canonical form of a path with all intermediate components
984 /// normalized and symbolic links resolved.
985 #[unstable(feature = "fs_canonicalize", reason = "recently added API")]
986 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
987     fs_imp::canonicalize(path.as_ref())
988 }
989
990 /// Creates a new, empty directory at the provided path
991 ///
992 /// # Errors
993 ///
994 /// This function will return an error if the user lacks permissions to make a
995 /// new directory at the provided `path`, or if the directory already exists.
996 ///
997 /// # Examples
998 ///
999 /// ```
1000 /// use std::fs;
1001 ///
1002 /// # fn foo() -> std::io::Result<()> {
1003 /// try!(fs::create_dir("/some/dir"));
1004 /// # Ok(())
1005 /// # }
1006 /// ```
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1009     DirBuilder::new().create(path.as_ref())
1010 }
1011
1012 /// Recursively create a directory and all of its parent components if they
1013 /// are missing.
1014 ///
1015 /// # Errors
1016 ///
1017 /// This function will fail if any directory in the path specified by `path`
1018 /// does not already exist and it could not be created otherwise. The specific
1019 /// error conditions for when a directory is being created (after it is
1020 /// determined to not exist) are outlined by `fs::create_dir`.
1021 ///
1022 /// # Examples
1023 ///
1024 /// ```
1025 /// use std::fs;
1026 ///
1027 /// # fn foo() -> std::io::Result<()> {
1028 /// try!(fs::create_dir_all("/some/dir"));
1029 /// # Ok(())
1030 /// # }
1031 /// ```
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1034     DirBuilder::new().recursive(true).create(path.as_ref())
1035 }
1036
1037 /// Removes an existing, empty directory.
1038 ///
1039 /// # Errors
1040 ///
1041 /// This function will return an error if the user lacks permissions to remove
1042 /// the directory at the provided `path`, or if the directory isn't empty.
1043 ///
1044 /// # Examples
1045 ///
1046 /// ```
1047 /// use std::fs;
1048 ///
1049 /// # fn foo() -> std::io::Result<()> {
1050 /// try!(fs::remove_dir("/some/dir"));
1051 /// # Ok(())
1052 /// # }
1053 /// ```
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1056     fs_imp::rmdir(path.as_ref())
1057 }
1058
1059 /// Removes a directory at this path, after removing all its contents. Use
1060 /// carefully!
1061 ///
1062 /// This function does **not** follow symbolic links and it will simply remove the
1063 /// symbolic link itself.
1064 ///
1065 /// # Errors
1066 ///
1067 /// See `file::remove_file` and `fs::remove_dir`.
1068 ///
1069 /// # Examples
1070 ///
1071 /// ```
1072 /// use std::fs;
1073 ///
1074 /// # fn foo() -> std::io::Result<()> {
1075 /// try!(fs::remove_dir_all("/some/dir"));
1076 /// # Ok(())
1077 /// # }
1078 /// ```
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1081     let path = path.as_ref();
1082     for child in try!(read_dir(path)) {
1083         let child = try!(child).path();
1084         let stat = try!(symlink_metadata(&*child));
1085         if stat.is_dir() {
1086             try!(remove_dir_all(&*child));
1087         } else {
1088             try!(remove_file(&*child));
1089         }
1090     }
1091     remove_dir(path)
1092 }
1093
1094 /// Returns an iterator over the entries within a directory.
1095 ///
1096 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1097 /// be encountered after an iterator is initially constructed.
1098 ///
1099 /// # Examples
1100 ///
1101 /// ```
1102 /// use std::io;
1103 /// use std::fs::{self, DirEntry};
1104 /// use std::path::Path;
1105 ///
1106 /// // one possible implementation of fs::walk_dir only visiting files
1107 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1108 ///     if try!(fs::metadata(dir)).is_dir() {
1109 ///         for entry in try!(fs::read_dir(dir)) {
1110 ///             let entry = try!(entry);
1111 ///             if try!(fs::metadata(entry.path())).is_dir() {
1112 ///                 try!(visit_dirs(&entry.path(), cb));
1113 ///             } else {
1114 ///                 cb(&entry);
1115 ///             }
1116 ///         }
1117 ///     }
1118 ///     Ok(())
1119 /// }
1120 /// ```
1121 ///
1122 /// # Errors
1123 ///
1124 /// This function will return an error if the provided `path` doesn't exist, if
1125 /// the process lacks permissions to view the contents or if the `path` points
1126 /// at a non-directory file
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1129     fs_imp::readdir(path.as_ref()).map(ReadDir)
1130 }
1131
1132 /// Returns an iterator that will recursively walk the directory structure
1133 /// rooted at `path`.
1134 ///
1135 /// The path given will not be iterated over, and this will perform iteration in
1136 /// some top-down order.  The contents of unreadable subdirectories are ignored.
1137 ///
1138 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1139 /// be encountered after an iterator is initially constructed.
1140 #[unstable(feature = "fs_walk",
1141            reason = "the precise semantics and defaults for a recursive walk \
1142                      may change and this may end up accounting for files such \
1143                      as symlinks differently")]
1144 pub fn walk_dir<P: AsRef<Path>>(path: P) -> io::Result<WalkDir> {
1145     let start = try!(read_dir(path));
1146     Ok(WalkDir { cur: Some(start), stack: Vec::new() })
1147 }
1148
1149 #[unstable(feature = "fs_walk")]
1150 impl Iterator for WalkDir {
1151     type Item = io::Result<DirEntry>;
1152
1153     fn next(&mut self) -> Option<io::Result<DirEntry>> {
1154         loop {
1155             if let Some(ref mut cur) = self.cur {
1156                 match cur.next() {
1157                     Some(Err(e)) => return Some(Err(e)),
1158                     Some(Ok(next)) => {
1159                         let path = next.path();
1160                         if path.is_dir() {
1161                             self.stack.push(read_dir(&*path));
1162                         }
1163                         return Some(Ok(next))
1164                     }
1165                     None => {}
1166                 }
1167             }
1168             self.cur = None;
1169             match self.stack.pop() {
1170                 Some(Err(e)) => return Some(Err(e)),
1171                 Some(Ok(next)) => self.cur = Some(next),
1172                 None => return None,
1173             }
1174         }
1175     }
1176 }
1177
1178 /// Utility methods for paths.
1179 #[unstable(feature = "path_ext",
1180            reason = "The precise set of methods exposed on this trait may \
1181                      change and some methods may be removed.  For stable code, \
1182                      see the std::fs::metadata function.")]
1183 pub trait PathExt {
1184     /// Gets information on the file, directory, etc at this path.
1185     ///
1186     /// Consult the `fs::metadata` documentation for more info.
1187     ///
1188     /// This call preserves identical runtime/error semantics with
1189     /// `fs::metadata`.
1190     fn metadata(&self) -> io::Result<Metadata>;
1191
1192     /// Gets information on the file, directory, etc at this path.
1193     ///
1194     /// Consult the `fs::symlink_metadata` documentation for more info.
1195     ///
1196     /// This call preserves identical runtime/error semantics with
1197     /// `fs::symlink_metadata`.
1198     fn symlink_metadata(&self) -> io::Result<Metadata>;
1199
1200     /// Returns the canonical form of a path, normalizing all components and
1201     /// eliminate all symlinks.
1202     ///
1203     /// This call preserves identical runtime/error semantics with
1204     /// `fs::canonicalize`.
1205     fn canonicalize(&self) -> io::Result<PathBuf>;
1206
1207     /// Reads the symlink at this path.
1208     ///
1209     /// For more information see `fs::read_link`.
1210     fn read_link(&self) -> io::Result<PathBuf>;
1211
1212     /// Reads the directory at this path.
1213     ///
1214     /// For more information see `fs::read_dir`.
1215     fn read_dir(&self) -> io::Result<ReadDir>;
1216
1217     /// Boolean value indicator whether the underlying file exists on the local
1218     /// filesystem. Returns false in exactly the cases where `fs::stat` fails.
1219     fn exists(&self) -> bool;
1220
1221     /// Whether the underlying implementation (be it a file path, or something
1222     /// else) points at a "regular file" on the FS. Will return false for paths
1223     /// to non-existent locations or directories or other non-regular files
1224     /// (named pipes, etc). Follows links when making this determination.
1225     fn is_file(&self) -> bool;
1226
1227     /// Whether the underlying implementation (be it a file path, or something
1228     /// else) is pointing at a directory in the underlying FS. Will return
1229     /// false for paths to non-existent locations or if the item is not a
1230     /// directory (eg files, named pipes, etc). Follows links when making this
1231     /// determination.
1232     fn is_dir(&self) -> bool;
1233 }
1234
1235 impl PathExt for Path {
1236     fn metadata(&self) -> io::Result<Metadata> { metadata(self) }
1237     fn symlink_metadata(&self) -> io::Result<Metadata> { symlink_metadata(self) }
1238     fn canonicalize(&self) -> io::Result<PathBuf> { canonicalize(self) }
1239     fn read_link(&self) -> io::Result<PathBuf> { read_link(self) }
1240     fn read_dir(&self) -> io::Result<ReadDir> { read_dir(self) }
1241     fn exists(&self) -> bool { metadata(self).is_ok() }
1242
1243     fn is_file(&self) -> bool {
1244         metadata(self).map(|s| s.is_file()).unwrap_or(false)
1245     }
1246
1247     fn is_dir(&self) -> bool {
1248         metadata(self).map(|s| s.is_dir()).unwrap_or(false)
1249     }
1250 }
1251
1252 /// Changes the timestamps for a file's last modification and access time.
1253 ///
1254 /// The file at the path specified will have its last access time set to
1255 /// `accessed` and its modification time set to `modified`. The times specified
1256 /// should be in milliseconds.
1257 #[unstable(feature = "fs_time",
1258            reason = "the argument type of u64 is not quite appropriate for \
1259                      this function and may change if the standard library \
1260                      gains a type to represent a moment in time")]
1261 pub fn set_file_times<P: AsRef<Path>>(path: P, accessed: u64,
1262                                  modified: u64) -> io::Result<()> {
1263     fs_imp::utimes(path.as_ref(), accessed, modified)
1264 }
1265
1266 /// Changes the permissions found on a file or a directory.
1267 ///
1268 /// # Examples
1269 ///
1270 /// ```
1271 /// # #![feature(fs)]
1272 /// # fn foo() -> std::io::Result<()> {
1273 /// use std::fs;
1274 ///
1275 /// let mut perms = try!(fs::metadata("foo.txt")).permissions();
1276 /// perms.set_readonly(true);
1277 /// try!(fs::set_permissions("foo.txt", perms));
1278 /// # Ok(())
1279 /// # }
1280 /// ```
1281 ///
1282 /// # Errors
1283 ///
1284 /// This function will return an error if the provided `path` doesn't exist, if
1285 /// the process lacks permissions to change the attributes of the file, or if
1286 /// some other I/O error is encountered.
1287 #[unstable(feature = "fs",
1288            reason = "a more granual ability to set specific permissions may \
1289                      be exposed on the Permissions structure itself and this \
1290                      method may not always exist")]
1291 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
1292     fs_imp::set_perm(path.as_ref(), perm.0)
1293 }
1294
1295 impl DirBuilder {
1296     /// Creates a new set of options with default mode/security settings for all
1297     /// platforms and also non-recursive.
1298     pub fn new() -> DirBuilder {
1299         DirBuilder {
1300             inner: fs_imp::DirBuilder::new(),
1301             recursive: false,
1302         }
1303     }
1304
1305     /// Indicate that directories create should be created recursively, creating
1306     /// all parent directories if they do not exist with the same security and
1307     /// permissions settings.
1308     ///
1309     /// This option defaults to `false`
1310     pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1311         self.recursive = recursive;
1312         self
1313     }
1314
1315     /// Create the specified directory with the options configured in this
1316     /// builder.
1317     pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1318         let path = path.as_ref();
1319         if self.recursive {
1320             self.create_dir_all(path)
1321         } else {
1322             self.inner.mkdir(path)
1323         }
1324     }
1325
1326     fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1327         if path == Path::new("") || path.is_dir() { return Ok(()) }
1328         if let Some(p) = path.parent() {
1329             try!(self.create_dir_all(p))
1330         }
1331         self.inner.mkdir(path)
1332     }
1333 }
1334
1335 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1336     fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1337         &mut self.inner
1338     }
1339 }
1340
1341 #[cfg(test)]
1342 mod tests {
1343     #![allow(deprecated)] //rand
1344
1345     use prelude::v1::*;
1346     use io::prelude::*;
1347
1348     use env;
1349     use fs::{self, File, OpenOptions};
1350     use io::{ErrorKind, SeekFrom};
1351     use path::PathBuf;
1352     use path::Path as Path2;
1353     use os;
1354     use rand::{self, StdRng, Rng};
1355     use str;
1356
1357     macro_rules! check { ($e:expr) => (
1358         match $e {
1359             Ok(t) => t,
1360             Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1361         }
1362     ) }
1363
1364     macro_rules! error { ($e:expr, $s:expr) => (
1365         match $e {
1366             Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1367             Err(ref err) => assert!(err.to_string().contains($s),
1368                                     format!("`{}` did not contain `{}`", err, $s))
1369         }
1370     ) }
1371
1372     pub struct TempDir(PathBuf);
1373
1374     impl TempDir {
1375         fn join(&self, path: &str) -> PathBuf {
1376             let TempDir(ref p) = *self;
1377             p.join(path)
1378         }
1379
1380         fn path<'a>(&'a self) -> &'a Path2 {
1381             let TempDir(ref p) = *self;
1382             p
1383         }
1384     }
1385
1386     impl Drop for TempDir {
1387         fn drop(&mut self) {
1388             // Gee, seeing how we're testing the fs module I sure hope that we
1389             // at least implement this correctly!
1390             let TempDir(ref p) = *self;
1391             check!(fs::remove_dir_all(p));
1392         }
1393     }
1394
1395     pub fn tmpdir() -> TempDir {
1396         let p = env::temp_dir();
1397         let mut r = rand::thread_rng();
1398         let ret = p.join(&format!("rust-{}", r.next_u32()));
1399         check!(fs::create_dir(&ret));
1400         TempDir(ret)
1401     }
1402
1403     #[test]
1404     fn file_test_io_smoke_test() {
1405         let message = "it's alright. have a good time";
1406         let tmpdir = tmpdir();
1407         let filename = &tmpdir.join("file_rt_io_file_test.txt");
1408         {
1409             let mut write_stream = check!(File::create(filename));
1410             check!(write_stream.write(message.as_bytes()));
1411         }
1412         {
1413             let mut read_stream = check!(File::open(filename));
1414             let mut read_buf = [0; 1028];
1415             let read_str = match check!(read_stream.read(&mut read_buf)) {
1416                 0 => panic!("shouldn't happen"),
1417                 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1418             };
1419             assert_eq!(read_str, message);
1420         }
1421         check!(fs::remove_file(filename));
1422     }
1423
1424     #[test]
1425     fn invalid_path_raises() {
1426         let tmpdir = tmpdir();
1427         let filename = &tmpdir.join("file_that_does_not_exist.txt");
1428         let result = File::open(filename);
1429
1430         if cfg!(unix) {
1431             error!(result, "o such file or directory");
1432         }
1433         // error!(result, "couldn't open path as file");
1434         // error!(result, format!("path={}; mode=open; access=read", filename.display()));
1435     }
1436
1437     #[test]
1438     fn file_test_iounlinking_invalid_path_should_raise_condition() {
1439         let tmpdir = tmpdir();
1440         let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1441
1442         let result = fs::remove_file(filename);
1443
1444         if cfg!(unix) {
1445             error!(result, "o such file or directory");
1446         }
1447         // error!(result, "couldn't unlink path");
1448         // error!(result, format!("path={}", filename.display()));
1449     }
1450
1451     #[test]
1452     fn file_test_io_non_positional_read() {
1453         let message: &str = "ten-four";
1454         let mut read_mem = [0; 8];
1455         let tmpdir = tmpdir();
1456         let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1457         {
1458             let mut rw_stream = check!(File::create(filename));
1459             check!(rw_stream.write(message.as_bytes()));
1460         }
1461         {
1462             let mut read_stream = check!(File::open(filename));
1463             {
1464                 let read_buf = &mut read_mem[0..4];
1465                 check!(read_stream.read(read_buf));
1466             }
1467             {
1468                 let read_buf = &mut read_mem[4..8];
1469                 check!(read_stream.read(read_buf));
1470             }
1471         }
1472         check!(fs::remove_file(filename));
1473         let read_str = str::from_utf8(&read_mem).unwrap();
1474         assert_eq!(read_str, message);
1475     }
1476
1477     #[test]
1478     fn file_test_io_seek_and_tell_smoke_test() {
1479         let message = "ten-four";
1480         let mut read_mem = [0; 4];
1481         let set_cursor = 4 as u64;
1482         let mut tell_pos_pre_read;
1483         let mut tell_pos_post_read;
1484         let tmpdir = tmpdir();
1485         let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1486         {
1487             let mut rw_stream = check!(File::create(filename));
1488             check!(rw_stream.write(message.as_bytes()));
1489         }
1490         {
1491             let mut read_stream = check!(File::open(filename));
1492             check!(read_stream.seek(SeekFrom::Start(set_cursor)));
1493             tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
1494             check!(read_stream.read(&mut read_mem));
1495             tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
1496         }
1497         check!(fs::remove_file(filename));
1498         let read_str = str::from_utf8(&read_mem).unwrap();
1499         assert_eq!(read_str, &message[4..8]);
1500         assert_eq!(tell_pos_pre_read, set_cursor);
1501         assert_eq!(tell_pos_post_read, message.len() as u64);
1502     }
1503
1504     #[test]
1505     fn file_test_io_seek_and_write() {
1506         let initial_msg =   "food-is-yummy";
1507         let overwrite_msg =    "-the-bar!!";
1508         let final_msg =     "foo-the-bar!!";
1509         let seek_idx = 3;
1510         let mut read_mem = [0; 13];
1511         let tmpdir = tmpdir();
1512         let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1513         {
1514             let mut rw_stream = check!(File::create(filename));
1515             check!(rw_stream.write(initial_msg.as_bytes()));
1516             check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
1517             check!(rw_stream.write(overwrite_msg.as_bytes()));
1518         }
1519         {
1520             let mut read_stream = check!(File::open(filename));
1521             check!(read_stream.read(&mut read_mem));
1522         }
1523         check!(fs::remove_file(filename));
1524         let read_str = str::from_utf8(&read_mem).unwrap();
1525         assert!(read_str == final_msg);
1526     }
1527
1528     #[test]
1529     fn file_test_io_seek_shakedown() {
1530         //                   01234567890123
1531         let initial_msg =   "qwer-asdf-zxcv";
1532         let chunk_one: &str = "qwer";
1533         let chunk_two: &str = "asdf";
1534         let chunk_three: &str = "zxcv";
1535         let mut read_mem = [0; 4];
1536         let tmpdir = tmpdir();
1537         let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1538         {
1539             let mut rw_stream = check!(File::create(filename));
1540             check!(rw_stream.write(initial_msg.as_bytes()));
1541         }
1542         {
1543             let mut read_stream = check!(File::open(filename));
1544
1545             check!(read_stream.seek(SeekFrom::End(-4)));
1546             check!(read_stream.read(&mut read_mem));
1547             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
1548
1549             check!(read_stream.seek(SeekFrom::Current(-9)));
1550             check!(read_stream.read(&mut read_mem));
1551             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
1552
1553             check!(read_stream.seek(SeekFrom::Start(0)));
1554             check!(read_stream.read(&mut read_mem));
1555             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
1556         }
1557         check!(fs::remove_file(filename));
1558     }
1559
1560     #[test]
1561     fn file_test_stat_is_correct_on_is_file() {
1562         let tmpdir = tmpdir();
1563         let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1564         {
1565             let mut opts = OpenOptions::new();
1566             let mut fs = check!(opts.read(true).write(true)
1567                                     .create(true).open(filename));
1568             let msg = "hw";
1569             fs.write(msg.as_bytes()).unwrap();
1570
1571             let fstat_res = check!(fs.metadata());
1572             assert!(fstat_res.is_file());
1573         }
1574         let stat_res_fn = check!(fs::metadata(filename));
1575         assert!(stat_res_fn.is_file());
1576         let stat_res_meth = check!(filename.metadata());
1577         assert!(stat_res_meth.is_file());
1578         check!(fs::remove_file(filename));
1579     }
1580
1581     #[test]
1582     fn file_test_stat_is_correct_on_is_dir() {
1583         let tmpdir = tmpdir();
1584         let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1585         check!(fs::create_dir(filename));
1586         let stat_res_fn = check!(fs::metadata(filename));
1587         assert!(stat_res_fn.is_dir());
1588         let stat_res_meth = check!(filename.metadata());
1589         assert!(stat_res_meth.is_dir());
1590         check!(fs::remove_dir(filename));
1591     }
1592
1593     #[test]
1594     fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1595         let tmpdir = tmpdir();
1596         let dir = &tmpdir.join("fileinfo_false_on_dir");
1597         check!(fs::create_dir(dir));
1598         assert!(dir.is_file() == false);
1599         check!(fs::remove_dir(dir));
1600     }
1601
1602     #[test]
1603     fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1604         let tmpdir = tmpdir();
1605         let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1606         check!(check!(File::create(file)).write(b"foo"));
1607         assert!(file.exists());
1608         check!(fs::remove_file(file));
1609         assert!(!file.exists());
1610     }
1611
1612     #[test]
1613     fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1614         let tmpdir = tmpdir();
1615         let dir = &tmpdir.join("before_and_after_dir");
1616         assert!(!dir.exists());
1617         check!(fs::create_dir(dir));
1618         assert!(dir.exists());
1619         assert!(dir.is_dir());
1620         check!(fs::remove_dir(dir));
1621         assert!(!dir.exists());
1622     }
1623
1624     #[test]
1625     fn file_test_directoryinfo_readdir() {
1626         let tmpdir = tmpdir();
1627         let dir = &tmpdir.join("di_readdir");
1628         check!(fs::create_dir(dir));
1629         let prefix = "foo";
1630         for n in 0..3 {
1631             let f = dir.join(&format!("{}.txt", n));
1632             let mut w = check!(File::create(&f));
1633             let msg_str = format!("{}{}", prefix, n.to_string());
1634             let msg = msg_str.as_bytes();
1635             check!(w.write(msg));
1636         }
1637         let files = check!(fs::read_dir(dir));
1638         let mut mem = [0; 4];
1639         for f in files {
1640             let f = f.unwrap().path();
1641             {
1642                 let n = f.file_stem().unwrap();
1643                 check!(check!(File::open(&f)).read(&mut mem));
1644                 let read_str = str::from_utf8(&mem).unwrap();
1645                 let expected = format!("{}{}", prefix, n.to_str().unwrap());
1646                 assert_eq!(expected, read_str);
1647             }
1648             check!(fs::remove_file(&f));
1649         }
1650         check!(fs::remove_dir(dir));
1651     }
1652
1653     #[test]
1654     fn file_test_walk_dir() {
1655         let tmpdir = tmpdir();
1656         let dir = &tmpdir.join("walk_dir");
1657         check!(fs::create_dir(dir));
1658
1659         let dir1 = &dir.join("01/02/03");
1660         check!(fs::create_dir_all(dir1));
1661         check!(File::create(&dir1.join("04")));
1662
1663         let dir2 = &dir.join("11/12/13");
1664         check!(fs::create_dir_all(dir2));
1665         check!(File::create(&dir2.join("14")));
1666
1667         let files = check!(fs::walk_dir(dir));
1668         let mut cur = [0; 2];
1669         for f in files {
1670             let f = f.unwrap().path();
1671             let stem = f.file_stem().unwrap().to_str().unwrap();
1672             let root = stem.as_bytes()[0] - b'0';
1673             let name = stem.as_bytes()[1] - b'0';
1674             assert!(cur[root as usize] < name);
1675             cur[root as usize] = name;
1676         }
1677
1678         check!(fs::remove_dir_all(dir));
1679     }
1680
1681     #[test]
1682     fn mkdir_path_already_exists_error() {
1683         let tmpdir = tmpdir();
1684         let dir = &tmpdir.join("mkdir_error_twice");
1685         check!(fs::create_dir(dir));
1686         let e = fs::create_dir(dir).err().unwrap();
1687         assert_eq!(e.kind(), ErrorKind::AlreadyExists);
1688     }
1689
1690     #[test]
1691     fn recursive_mkdir() {
1692         let tmpdir = tmpdir();
1693         let dir = tmpdir.join("d1/d2");
1694         check!(fs::create_dir_all(&dir));
1695         assert!(dir.is_dir())
1696     }
1697
1698     #[test]
1699     fn recursive_mkdir_failure() {
1700         let tmpdir = tmpdir();
1701         let dir = tmpdir.join("d1");
1702         let file = dir.join("f1");
1703
1704         check!(fs::create_dir_all(&dir));
1705         check!(File::create(&file));
1706
1707         let result = fs::create_dir_all(&file);
1708
1709         assert!(result.is_err());
1710         // error!(result, "couldn't recursively mkdir");
1711         // error!(result, "couldn't create directory");
1712         // error!(result, "mode=0700");
1713         // error!(result, format!("path={}", file.display()));
1714     }
1715
1716     #[test]
1717     fn recursive_mkdir_slash() {
1718         check!(fs::create_dir_all(&Path2::new("/")));
1719     }
1720
1721     // FIXME(#12795) depends on lstat to work on windows
1722     #[cfg(not(windows))]
1723     #[test]
1724     fn recursive_rmdir() {
1725         let tmpdir = tmpdir();
1726         let d1 = tmpdir.join("d1");
1727         let dt = d1.join("t");
1728         let dtt = dt.join("t");
1729         let d2 = tmpdir.join("d2");
1730         let canary = d2.join("do_not_delete");
1731         check!(fs::create_dir_all(&dtt));
1732         check!(fs::create_dir_all(&d2));
1733         check!(check!(File::create(&canary)).write(b"foo"));
1734         check!(fs::soft_link(&d2, &dt.join("d2")));
1735         check!(fs::remove_dir_all(&d1));
1736
1737         assert!(!d1.is_dir());
1738         assert!(canary.exists());
1739     }
1740
1741     #[test]
1742     fn unicode_path_is_dir() {
1743         assert!(Path2::new(".").is_dir());
1744         assert!(!Path2::new("test/stdtest/fs.rs").is_dir());
1745
1746         let tmpdir = tmpdir();
1747
1748         let mut dirpath = tmpdir.path().to_path_buf();
1749         dirpath.push(&format!("test-가一ー你好"));
1750         check!(fs::create_dir(&dirpath));
1751         assert!(dirpath.is_dir());
1752
1753         let mut filepath = dirpath;
1754         filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
1755         check!(File::create(&filepath)); // ignore return; touch only
1756         assert!(!filepath.is_dir());
1757         assert!(filepath.exists());
1758     }
1759
1760     #[test]
1761     fn unicode_path_exists() {
1762         assert!(Path2::new(".").exists());
1763         assert!(!Path2::new("test/nonexistent-bogus-path").exists());
1764
1765         let tmpdir = tmpdir();
1766         let unicode = tmpdir.path();
1767         let unicode = unicode.join(&format!("test-각丁ー再见"));
1768         check!(fs::create_dir(&unicode));
1769         assert!(unicode.exists());
1770         assert!(!Path2::new("test/unicode-bogus-path-각丁ー再见").exists());
1771     }
1772
1773     #[test]
1774     fn copy_file_does_not_exist() {
1775         let from = Path2::new("test/nonexistent-bogus-path");
1776         let to = Path2::new("test/other-bogus-path");
1777
1778         match fs::copy(&from, &to) {
1779             Ok(..) => panic!(),
1780             Err(..) => {
1781                 assert!(!from.exists());
1782                 assert!(!to.exists());
1783             }
1784         }
1785     }
1786
1787     #[test]
1788     fn copy_file_ok() {
1789         let tmpdir = tmpdir();
1790         let input = tmpdir.join("in.txt");
1791         let out = tmpdir.join("out.txt");
1792
1793         check!(check!(File::create(&input)).write(b"hello"));
1794         check!(fs::copy(&input, &out));
1795         let mut v = Vec::new();
1796         check!(check!(File::open(&out)).read_to_end(&mut v));
1797         assert_eq!(v, b"hello");
1798
1799         assert_eq!(check!(input.metadata()).permissions(),
1800                    check!(out.metadata()).permissions());
1801     }
1802
1803     #[test]
1804     fn copy_file_dst_dir() {
1805         let tmpdir = tmpdir();
1806         let out = tmpdir.join("out");
1807
1808         check!(File::create(&out));
1809         match fs::copy(&*out, tmpdir.path()) {
1810             Ok(..) => panic!(), Err(..) => {}
1811         }
1812     }
1813
1814     #[test]
1815     fn copy_file_dst_exists() {
1816         let tmpdir = tmpdir();
1817         let input = tmpdir.join("in");
1818         let output = tmpdir.join("out");
1819
1820         check!(check!(File::create(&input)).write("foo".as_bytes()));
1821         check!(check!(File::create(&output)).write("bar".as_bytes()));
1822         check!(fs::copy(&input, &output));
1823
1824         let mut v = Vec::new();
1825         check!(check!(File::open(&output)).read_to_end(&mut v));
1826         assert_eq!(v, b"foo".to_vec());
1827     }
1828
1829     #[test]
1830     fn copy_file_src_dir() {
1831         let tmpdir = tmpdir();
1832         let out = tmpdir.join("out");
1833
1834         match fs::copy(tmpdir.path(), &out) {
1835             Ok(..) => panic!(), Err(..) => {}
1836         }
1837         assert!(!out.exists());
1838     }
1839
1840     #[test]
1841     fn copy_file_preserves_perm_bits() {
1842         let tmpdir = tmpdir();
1843         let input = tmpdir.join("in.txt");
1844         let out = tmpdir.join("out.txt");
1845
1846         let attr = check!(check!(File::create(&input)).metadata());
1847         let mut p = attr.permissions();
1848         p.set_readonly(true);
1849         check!(fs::set_permissions(&input, p));
1850         check!(fs::copy(&input, &out));
1851         assert!(check!(out.metadata()).permissions().readonly());
1852         check!(fs::set_permissions(&input, attr.permissions()));
1853         check!(fs::set_permissions(&out, attr.permissions()));
1854     }
1855
1856     #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
1857     #[test]
1858     fn symlinks_work() {
1859         let tmpdir = tmpdir();
1860         let input = tmpdir.join("in.txt");
1861         let out = tmpdir.join("out.txt");
1862
1863         check!(check!(File::create(&input)).write("foobar".as_bytes()));
1864         check!(fs::soft_link(&input, &out));
1865         // if cfg!(not(windows)) {
1866         //     assert_eq!(check!(lstat(&out)).kind, FileType::Symlink);
1867         //     assert_eq!(check!(out.lstat()).kind, FileType::Symlink);
1868         // }
1869         assert_eq!(check!(fs::metadata(&out)).len(),
1870                    check!(fs::metadata(&input)).len());
1871         let mut v = Vec::new();
1872         check!(check!(File::open(&out)).read_to_end(&mut v));
1873         assert_eq!(v, b"foobar".to_vec());
1874     }
1875
1876     #[cfg(not(windows))] // apparently windows doesn't like symlinks
1877     #[test]
1878     fn symlink_noexist() {
1879         let tmpdir = tmpdir();
1880         // symlinks can point to things that don't exist
1881         check!(fs::soft_link(&tmpdir.join("foo"), &tmpdir.join("bar")));
1882         assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))),
1883                    tmpdir.join("foo"));
1884     }
1885
1886     #[test]
1887     fn readlink_not_symlink() {
1888         let tmpdir = tmpdir();
1889         match fs::read_link(tmpdir.path()) {
1890             Ok(..) => panic!("wanted a failure"),
1891             Err(..) => {}
1892         }
1893     }
1894
1895     #[test]
1896     fn links_work() {
1897         let tmpdir = tmpdir();
1898         let input = tmpdir.join("in.txt");
1899         let out = tmpdir.join("out.txt");
1900
1901         check!(check!(File::create(&input)).write("foobar".as_bytes()));
1902         check!(fs::hard_link(&input, &out));
1903         assert_eq!(check!(fs::metadata(&out)).len(),
1904                    check!(fs::metadata(&input)).len());
1905         assert_eq!(check!(fs::metadata(&out)).len(),
1906                    check!(input.metadata()).len());
1907         let mut v = Vec::new();
1908         check!(check!(File::open(&out)).read_to_end(&mut v));
1909         assert_eq!(v, b"foobar".to_vec());
1910
1911         // can't link to yourself
1912         match fs::hard_link(&input, &input) {
1913             Ok(..) => panic!("wanted a failure"),
1914             Err(..) => {}
1915         }
1916         // can't link to something that doesn't exist
1917         match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
1918             Ok(..) => panic!("wanted a failure"),
1919             Err(..) => {}
1920         }
1921     }
1922
1923     #[test]
1924     fn chmod_works() {
1925         let tmpdir = tmpdir();
1926         let file = tmpdir.join("in.txt");
1927
1928         check!(File::create(&file));
1929         let attr = check!(fs::metadata(&file));
1930         assert!(!attr.permissions().readonly());
1931         let mut p = attr.permissions();
1932         p.set_readonly(true);
1933         check!(fs::set_permissions(&file, p.clone()));
1934         let attr = check!(fs::metadata(&file));
1935         assert!(attr.permissions().readonly());
1936
1937         match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
1938             Ok(..) => panic!("wanted an error"),
1939             Err(..) => {}
1940         }
1941
1942         p.set_readonly(false);
1943         check!(fs::set_permissions(&file, p));
1944     }
1945
1946     #[test]
1947     fn sync_doesnt_kill_anything() {
1948         let tmpdir = tmpdir();
1949         let path = tmpdir.join("in.txt");
1950
1951         let mut file = check!(File::create(&path));
1952         check!(file.sync_all());
1953         check!(file.sync_data());
1954         check!(file.write(b"foo"));
1955         check!(file.sync_all());
1956         check!(file.sync_data());
1957     }
1958
1959     #[test]
1960     fn truncate_works() {
1961         let tmpdir = tmpdir();
1962         let path = tmpdir.join("in.txt");
1963
1964         let mut file = check!(File::create(&path));
1965         check!(file.write(b"foo"));
1966         check!(file.sync_all());
1967
1968         // Do some simple things with truncation
1969         assert_eq!(check!(file.metadata()).len(), 3);
1970         check!(file.set_len(10));
1971         assert_eq!(check!(file.metadata()).len(), 10);
1972         check!(file.write(b"bar"));
1973         check!(file.sync_all());
1974         assert_eq!(check!(file.metadata()).len(), 10);
1975
1976         let mut v = Vec::new();
1977         check!(check!(File::open(&path)).read_to_end(&mut v));
1978         assert_eq!(v, b"foobar\0\0\0\0".to_vec());
1979
1980         // Truncate to a smaller length, don't seek, and then write something.
1981         // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
1982         // past the end of the file).
1983         check!(file.set_len(2));
1984         assert_eq!(check!(file.metadata()).len(), 2);
1985         check!(file.write(b"wut"));
1986         check!(file.sync_all());
1987         assert_eq!(check!(file.metadata()).len(), 9);
1988         let mut v = Vec::new();
1989         check!(check!(File::open(&path)).read_to_end(&mut v));
1990         assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
1991     }
1992
1993     #[test]
1994     fn open_flavors() {
1995         use fs::OpenOptions as OO;
1996         fn c<T: Clone>(t: &T) -> T { t.clone() }
1997
1998         let tmpdir = tmpdir();
1999
2000         let mut r = OO::new(); r.read(true);
2001         let mut w = OO::new(); w.write(true);
2002         let mut rw = OO::new(); rw.write(true).read(true);
2003
2004         match r.open(&tmpdir.join("a")) {
2005             Ok(..) => panic!(), Err(..) => {}
2006         }
2007
2008         // Perform each one twice to make sure that it succeeds the second time
2009         // (where the file exists)
2010         check!(c(&w).create(true).open(&tmpdir.join("b")));
2011         assert!(tmpdir.join("b").exists());
2012         check!(c(&w).create(true).open(&tmpdir.join("b")));
2013         check!(w.open(&tmpdir.join("b")));
2014
2015         check!(c(&rw).create(true).open(&tmpdir.join("c")));
2016         assert!(tmpdir.join("c").exists());
2017         check!(c(&rw).create(true).open(&tmpdir.join("c")));
2018         check!(rw.open(&tmpdir.join("c")));
2019
2020         check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2021         assert!(tmpdir.join("d").exists());
2022         check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2023         check!(c(&w).append(true).open(&tmpdir.join("d")));
2024
2025         check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2026         assert!(tmpdir.join("e").exists());
2027         check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2028         check!(c(&rw).append(true).open(&tmpdir.join("e")));
2029
2030         check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2031         assert!(tmpdir.join("f").exists());
2032         check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2033         check!(c(&w).truncate(true).open(&tmpdir.join("f")));
2034
2035         check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2036         assert!(tmpdir.join("g").exists());
2037         check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2038         check!(c(&rw).truncate(true).open(&tmpdir.join("g")));
2039
2040         check!(check!(File::create(&tmpdir.join("h"))).write("foo".as_bytes()));
2041         check!(r.open(&tmpdir.join("h")));
2042         {
2043             let mut f = check!(r.open(&tmpdir.join("h")));
2044             assert!(f.write("wut".as_bytes()).is_err());
2045         }
2046         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2047         {
2048             let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
2049             check!(f.write("bar".as_bytes()));
2050         }
2051         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
2052         {
2053             let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
2054             check!(f.write("bar".as_bytes()));
2055         }
2056         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2057     }
2058
2059     #[test]
2060     fn utime() {
2061         let tmpdir = tmpdir();
2062         let path = tmpdir.join("a");
2063         check!(File::create(&path));
2064         // These numbers have to be bigger than the time in the day to account
2065         // for timezones Windows in particular will fail in certain timezones
2066         // with small enough values
2067         check!(fs::set_file_times(&path, 100000, 200000));
2068         assert_eq!(check!(path.metadata()).accessed(), 100000);
2069         assert_eq!(check!(path.metadata()).modified(), 200000);
2070     }
2071
2072     #[test]
2073     fn utime_noexist() {
2074         let tmpdir = tmpdir();
2075
2076         match fs::set_file_times(&tmpdir.join("a"), 100, 200) {
2077             Ok(..) => panic!(),
2078             Err(..) => {}
2079         }
2080     }
2081
2082     #[test]
2083     fn binary_file() {
2084         let mut bytes = [0; 1024];
2085         StdRng::new().unwrap().fill_bytes(&mut bytes);
2086
2087         let tmpdir = tmpdir();
2088
2089         check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
2090         let mut v = Vec::new();
2091         check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
2092         assert!(v == &bytes[..]);
2093     }
2094
2095     #[test]
2096     #[cfg(not(windows))]
2097     fn unlink_readonly() {
2098         let tmpdir = tmpdir();
2099         let path = tmpdir.join("file");
2100         check!(File::create(&path));
2101         let mut perm = check!(fs::metadata(&path)).permissions();
2102         perm.set_readonly(true);
2103         check!(fs::set_permissions(&path, perm));
2104         check!(fs::remove_file(&path));
2105     }
2106
2107     #[test]
2108     fn mkdir_trailing_slash() {
2109         let tmpdir = tmpdir();
2110         let path = tmpdir.join("file");
2111         check!(fs::create_dir_all(&path.join("a/")));
2112     }
2113
2114     #[test]
2115     #[cfg(not(windows))]
2116     fn realpath_works() {
2117         let tmpdir = tmpdir();
2118         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2119         let file = tmpdir.join("test");
2120         let dir = tmpdir.join("test2");
2121         let link = dir.join("link");
2122         let linkdir = tmpdir.join("test3");
2123
2124         File::create(&file).unwrap();
2125         fs::create_dir(&dir).unwrap();
2126         fs::soft_link(&file, &link).unwrap();
2127         fs::soft_link(&dir, &linkdir).unwrap();
2128
2129         assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
2130
2131         assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
2132         assert_eq!(fs::canonicalize(&file).unwrap(), file);
2133         assert_eq!(fs::canonicalize(&link).unwrap(), file);
2134         assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
2135         assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
2136     }
2137
2138     #[test]
2139     #[cfg(not(windows))]
2140     fn realpath_works_tricky() {
2141         let tmpdir = tmpdir();
2142         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2143
2144         let a = tmpdir.join("a");
2145         let b = a.join("b");
2146         let c = b.join("c");
2147         let d = a.join("d");
2148         let e = d.join("e");
2149         let f = a.join("f");
2150
2151         fs::create_dir_all(&b).unwrap();
2152         fs::create_dir_all(&d).unwrap();
2153         File::create(&f).unwrap();
2154         fs::soft_link("../d/e", &c).unwrap();
2155         fs::soft_link("../f", &e).unwrap();
2156
2157         assert_eq!(fs::canonicalize(&c).unwrap(), f);
2158         assert_eq!(fs::canonicalize(&e).unwrap(), f);
2159     }
2160
2161     #[test]
2162     fn dir_entry_methods() {
2163         let tmpdir = tmpdir();
2164
2165         fs::create_dir_all(&tmpdir.join("a")).unwrap();
2166         File::create(&tmpdir.join("b")).unwrap();
2167
2168         for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
2169             let fname = file.file_name();
2170             match fname.to_str() {
2171                 Some("a") => {
2172                     assert!(file.file_type().unwrap().is_dir());
2173                     assert!(file.metadata().unwrap().is_dir());
2174                 }
2175                 Some("b") => {
2176                     assert!(file.file_type().unwrap().is_file());
2177                     assert!(file.metadata().unwrap().is_file());
2178                 }
2179                 f => panic!("unknown file name: {:?}", f),
2180             }
2181         }
2182     }
2183 }