]> git.lizzy.rs Git - rust.git/blob - src/libstd/fs.rs
doc: fix a broken link
[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")]
1182 pub trait PathExt {
1183     /// Gets information on the file, directory, etc at this path.
1184     ///
1185     /// Consult the `fs::metadata` documentation for more info.
1186     ///
1187     /// This call preserves identical runtime/error semantics with
1188     /// `fs::metadata`.
1189     fn metadata(&self) -> io::Result<Metadata>;
1190
1191     /// Gets information on the file, directory, etc at this path.
1192     ///
1193     /// Consult the `fs::symlink_metadata` documentation for more info.
1194     ///
1195     /// This call preserves identical runtime/error semantics with
1196     /// `fs::symlink_metadata`.
1197     fn symlink_metadata(&self) -> io::Result<Metadata>;
1198
1199     /// Returns the canonical form of a path, normalizing all components and
1200     /// eliminate all symlinks.
1201     ///
1202     /// This call preserves identical runtime/error semantics with
1203     /// `fs::canonicalize`.
1204     fn canonicalize(&self) -> io::Result<PathBuf>;
1205
1206     /// Reads the symlink at this path.
1207     ///
1208     /// For more information see `fs::read_link`.
1209     fn read_link(&self) -> io::Result<PathBuf>;
1210
1211     /// Reads the directory at this path.
1212     ///
1213     /// For more information see `fs::read_dir`.
1214     fn read_dir(&self) -> io::Result<ReadDir>;
1215
1216     /// Boolean value indicator whether the underlying file exists on the local
1217     /// filesystem. Returns false in exactly the cases where `fs::stat` fails.
1218     fn exists(&self) -> bool;
1219
1220     /// Whether the underlying implementation (be it a file path, or something
1221     /// else) points at a "regular file" on the FS. Will return false for paths
1222     /// to non-existent locations or directories or other non-regular files
1223     /// (named pipes, etc). Follows links when making this determination.
1224     fn is_file(&self) -> bool;
1225
1226     /// Whether the underlying implementation (be it a file path, or something
1227     /// else) is pointing at a directory in the underlying FS. Will return
1228     /// false for paths to non-existent locations or if the item is not a
1229     /// directory (eg files, named pipes, etc). Follows links when making this
1230     /// determination.
1231     fn is_dir(&self) -> bool;
1232 }
1233
1234 impl PathExt for Path {
1235     fn metadata(&self) -> io::Result<Metadata> { metadata(self) }
1236     fn symlink_metadata(&self) -> io::Result<Metadata> { symlink_metadata(self) }
1237     fn canonicalize(&self) -> io::Result<PathBuf> { canonicalize(self) }
1238     fn read_link(&self) -> io::Result<PathBuf> { read_link(self) }
1239     fn read_dir(&self) -> io::Result<ReadDir> { read_dir(self) }
1240     fn exists(&self) -> bool { metadata(self).is_ok() }
1241
1242     fn is_file(&self) -> bool {
1243         metadata(self).map(|s| s.is_file()).unwrap_or(false)
1244     }
1245
1246     fn is_dir(&self) -> bool {
1247         metadata(self).map(|s| s.is_dir()).unwrap_or(false)
1248     }
1249 }
1250
1251 /// Changes the timestamps for a file's last modification and access time.
1252 ///
1253 /// The file at the path specified will have its last access time set to
1254 /// `accessed` and its modification time set to `modified`. The times specified
1255 /// should be in milliseconds.
1256 #[unstable(feature = "fs_time",
1257            reason = "the argument type of u64 is not quite appropriate for \
1258                      this function and may change if the standard library \
1259                      gains a type to represent a moment in time")]
1260 pub fn set_file_times<P: AsRef<Path>>(path: P, accessed: u64,
1261                                  modified: u64) -> io::Result<()> {
1262     fs_imp::utimes(path.as_ref(), accessed, modified)
1263 }
1264
1265 /// Changes the permissions found on a file or a directory.
1266 ///
1267 /// # Examples
1268 ///
1269 /// ```
1270 /// # #![feature(fs)]
1271 /// # fn foo() -> std::io::Result<()> {
1272 /// use std::fs;
1273 ///
1274 /// let mut perms = try!(fs::metadata("foo.txt")).permissions();
1275 /// perms.set_readonly(true);
1276 /// try!(fs::set_permissions("foo.txt", perms));
1277 /// # Ok(())
1278 /// # }
1279 /// ```
1280 ///
1281 /// # Errors
1282 ///
1283 /// This function will return an error if the provided `path` doesn't exist, if
1284 /// the process lacks permissions to change the attributes of the file, or if
1285 /// some other I/O error is encountered.
1286 #[unstable(feature = "fs",
1287            reason = "a more granual ability to set specific permissions may \
1288                      be exposed on the Permissions structure itself and this \
1289                      method may not always exist")]
1290 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
1291     fs_imp::set_perm(path.as_ref(), perm.0)
1292 }
1293
1294 impl DirBuilder {
1295     /// Creates a new set of options with default mode/security settings for all
1296     /// platforms and also non-recursive.
1297     pub fn new() -> DirBuilder {
1298         DirBuilder {
1299             inner: fs_imp::DirBuilder::new(),
1300             recursive: false,
1301         }
1302     }
1303
1304     /// Indicate that directories create should be created recursively, creating
1305     /// all parent directories if they do not exist with the same security and
1306     /// permissions settings.
1307     ///
1308     /// This option defaults to `false`
1309     pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1310         self.recursive = recursive;
1311         self
1312     }
1313
1314     /// Create the specified directory with the options configured in this
1315     /// builder.
1316     pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1317         let path = path.as_ref();
1318         if self.recursive {
1319             self.create_dir_all(path)
1320         } else {
1321             self.inner.mkdir(path)
1322         }
1323     }
1324
1325     fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1326         if path == Path::new("") || path.is_dir() { return Ok(()) }
1327         if let Some(p) = path.parent() {
1328             try!(self.create_dir_all(p))
1329         }
1330         self.inner.mkdir(path)
1331     }
1332 }
1333
1334 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1335     fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1336         &mut self.inner
1337     }
1338 }
1339
1340 #[cfg(test)]
1341 mod tests {
1342     #![allow(deprecated)] //rand
1343
1344     use prelude::v1::*;
1345     use io::prelude::*;
1346
1347     use env;
1348     use fs::{self, File, OpenOptions};
1349     use io::{ErrorKind, SeekFrom};
1350     use path::PathBuf;
1351     use path::Path as Path2;
1352     use os;
1353     use rand::{self, StdRng, Rng};
1354     use str;
1355
1356     macro_rules! check { ($e:expr) => (
1357         match $e {
1358             Ok(t) => t,
1359             Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1360         }
1361     ) }
1362
1363     macro_rules! error { ($e:expr, $s:expr) => (
1364         match $e {
1365             Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1366             Err(ref err) => assert!(err.to_string().contains($s),
1367                                     format!("`{}` did not contain `{}`", err, $s))
1368         }
1369     ) }
1370
1371     pub struct TempDir(PathBuf);
1372
1373     impl TempDir {
1374         fn join(&self, path: &str) -> PathBuf {
1375             let TempDir(ref p) = *self;
1376             p.join(path)
1377         }
1378
1379         fn path<'a>(&'a self) -> &'a Path2 {
1380             let TempDir(ref p) = *self;
1381             p
1382         }
1383     }
1384
1385     impl Drop for TempDir {
1386         fn drop(&mut self) {
1387             // Gee, seeing how we're testing the fs module I sure hope that we
1388             // at least implement this correctly!
1389             let TempDir(ref p) = *self;
1390             check!(fs::remove_dir_all(p));
1391         }
1392     }
1393
1394     pub fn tmpdir() -> TempDir {
1395         let p = env::temp_dir();
1396         let mut r = rand::thread_rng();
1397         let ret = p.join(&format!("rust-{}", r.next_u32()));
1398         check!(fs::create_dir(&ret));
1399         TempDir(ret)
1400     }
1401
1402     #[test]
1403     fn file_test_io_smoke_test() {
1404         let message = "it's alright. have a good time";
1405         let tmpdir = tmpdir();
1406         let filename = &tmpdir.join("file_rt_io_file_test.txt");
1407         {
1408             let mut write_stream = check!(File::create(filename));
1409             check!(write_stream.write(message.as_bytes()));
1410         }
1411         {
1412             let mut read_stream = check!(File::open(filename));
1413             let mut read_buf = [0; 1028];
1414             let read_str = match check!(read_stream.read(&mut read_buf)) {
1415                 0 => panic!("shouldn't happen"),
1416                 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1417             };
1418             assert_eq!(read_str, message);
1419         }
1420         check!(fs::remove_file(filename));
1421     }
1422
1423     #[test]
1424     fn invalid_path_raises() {
1425         let tmpdir = tmpdir();
1426         let filename = &tmpdir.join("file_that_does_not_exist.txt");
1427         let result = File::open(filename);
1428
1429         if cfg!(unix) {
1430             error!(result, "o such file or directory");
1431         }
1432         // error!(result, "couldn't open path as file");
1433         // error!(result, format!("path={}; mode=open; access=read", filename.display()));
1434     }
1435
1436     #[test]
1437     fn file_test_iounlinking_invalid_path_should_raise_condition() {
1438         let tmpdir = tmpdir();
1439         let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1440
1441         let result = fs::remove_file(filename);
1442
1443         if cfg!(unix) {
1444             error!(result, "o such file or directory");
1445         }
1446         // error!(result, "couldn't unlink path");
1447         // error!(result, format!("path={}", filename.display()));
1448     }
1449
1450     #[test]
1451     fn file_test_io_non_positional_read() {
1452         let message: &str = "ten-four";
1453         let mut read_mem = [0; 8];
1454         let tmpdir = tmpdir();
1455         let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1456         {
1457             let mut rw_stream = check!(File::create(filename));
1458             check!(rw_stream.write(message.as_bytes()));
1459         }
1460         {
1461             let mut read_stream = check!(File::open(filename));
1462             {
1463                 let read_buf = &mut read_mem[0..4];
1464                 check!(read_stream.read(read_buf));
1465             }
1466             {
1467                 let read_buf = &mut read_mem[4..8];
1468                 check!(read_stream.read(read_buf));
1469             }
1470         }
1471         check!(fs::remove_file(filename));
1472         let read_str = str::from_utf8(&read_mem).unwrap();
1473         assert_eq!(read_str, message);
1474     }
1475
1476     #[test]
1477     fn file_test_io_seek_and_tell_smoke_test() {
1478         let message = "ten-four";
1479         let mut read_mem = [0; 4];
1480         let set_cursor = 4 as u64;
1481         let mut tell_pos_pre_read;
1482         let mut tell_pos_post_read;
1483         let tmpdir = tmpdir();
1484         let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1485         {
1486             let mut rw_stream = check!(File::create(filename));
1487             check!(rw_stream.write(message.as_bytes()));
1488         }
1489         {
1490             let mut read_stream = check!(File::open(filename));
1491             check!(read_stream.seek(SeekFrom::Start(set_cursor)));
1492             tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
1493             check!(read_stream.read(&mut read_mem));
1494             tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
1495         }
1496         check!(fs::remove_file(filename));
1497         let read_str = str::from_utf8(&read_mem).unwrap();
1498         assert_eq!(read_str, &message[4..8]);
1499         assert_eq!(tell_pos_pre_read, set_cursor);
1500         assert_eq!(tell_pos_post_read, message.len() as u64);
1501     }
1502
1503     #[test]
1504     fn file_test_io_seek_and_write() {
1505         let initial_msg =   "food-is-yummy";
1506         let overwrite_msg =    "-the-bar!!";
1507         let final_msg =     "foo-the-bar!!";
1508         let seek_idx = 3;
1509         let mut read_mem = [0; 13];
1510         let tmpdir = tmpdir();
1511         let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1512         {
1513             let mut rw_stream = check!(File::create(filename));
1514             check!(rw_stream.write(initial_msg.as_bytes()));
1515             check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
1516             check!(rw_stream.write(overwrite_msg.as_bytes()));
1517         }
1518         {
1519             let mut read_stream = check!(File::open(filename));
1520             check!(read_stream.read(&mut read_mem));
1521         }
1522         check!(fs::remove_file(filename));
1523         let read_str = str::from_utf8(&read_mem).unwrap();
1524         assert!(read_str == final_msg);
1525     }
1526
1527     #[test]
1528     fn file_test_io_seek_shakedown() {
1529         //                   01234567890123
1530         let initial_msg =   "qwer-asdf-zxcv";
1531         let chunk_one: &str = "qwer";
1532         let chunk_two: &str = "asdf";
1533         let chunk_three: &str = "zxcv";
1534         let mut read_mem = [0; 4];
1535         let tmpdir = tmpdir();
1536         let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1537         {
1538             let mut rw_stream = check!(File::create(filename));
1539             check!(rw_stream.write(initial_msg.as_bytes()));
1540         }
1541         {
1542             let mut read_stream = check!(File::open(filename));
1543
1544             check!(read_stream.seek(SeekFrom::End(-4)));
1545             check!(read_stream.read(&mut read_mem));
1546             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
1547
1548             check!(read_stream.seek(SeekFrom::Current(-9)));
1549             check!(read_stream.read(&mut read_mem));
1550             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
1551
1552             check!(read_stream.seek(SeekFrom::Start(0)));
1553             check!(read_stream.read(&mut read_mem));
1554             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
1555         }
1556         check!(fs::remove_file(filename));
1557     }
1558
1559     #[test]
1560     fn file_test_stat_is_correct_on_is_file() {
1561         let tmpdir = tmpdir();
1562         let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1563         {
1564             let mut opts = OpenOptions::new();
1565             let mut fs = check!(opts.read(true).write(true)
1566                                     .create(true).open(filename));
1567             let msg = "hw";
1568             fs.write(msg.as_bytes()).unwrap();
1569
1570             let fstat_res = check!(fs.metadata());
1571             assert!(fstat_res.is_file());
1572         }
1573         let stat_res_fn = check!(fs::metadata(filename));
1574         assert!(stat_res_fn.is_file());
1575         let stat_res_meth = check!(filename.metadata());
1576         assert!(stat_res_meth.is_file());
1577         check!(fs::remove_file(filename));
1578     }
1579
1580     #[test]
1581     fn file_test_stat_is_correct_on_is_dir() {
1582         let tmpdir = tmpdir();
1583         let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1584         check!(fs::create_dir(filename));
1585         let stat_res_fn = check!(fs::metadata(filename));
1586         assert!(stat_res_fn.is_dir());
1587         let stat_res_meth = check!(filename.metadata());
1588         assert!(stat_res_meth.is_dir());
1589         check!(fs::remove_dir(filename));
1590     }
1591
1592     #[test]
1593     fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1594         let tmpdir = tmpdir();
1595         let dir = &tmpdir.join("fileinfo_false_on_dir");
1596         check!(fs::create_dir(dir));
1597         assert!(dir.is_file() == false);
1598         check!(fs::remove_dir(dir));
1599     }
1600
1601     #[test]
1602     fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1603         let tmpdir = tmpdir();
1604         let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1605         check!(check!(File::create(file)).write(b"foo"));
1606         assert!(file.exists());
1607         check!(fs::remove_file(file));
1608         assert!(!file.exists());
1609     }
1610
1611     #[test]
1612     fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1613         let tmpdir = tmpdir();
1614         let dir = &tmpdir.join("before_and_after_dir");
1615         assert!(!dir.exists());
1616         check!(fs::create_dir(dir));
1617         assert!(dir.exists());
1618         assert!(dir.is_dir());
1619         check!(fs::remove_dir(dir));
1620         assert!(!dir.exists());
1621     }
1622
1623     #[test]
1624     fn file_test_directoryinfo_readdir() {
1625         let tmpdir = tmpdir();
1626         let dir = &tmpdir.join("di_readdir");
1627         check!(fs::create_dir(dir));
1628         let prefix = "foo";
1629         for n in 0..3 {
1630             let f = dir.join(&format!("{}.txt", n));
1631             let mut w = check!(File::create(&f));
1632             let msg_str = format!("{}{}", prefix, n.to_string());
1633             let msg = msg_str.as_bytes();
1634             check!(w.write(msg));
1635         }
1636         let files = check!(fs::read_dir(dir));
1637         let mut mem = [0; 4];
1638         for f in files {
1639             let f = f.unwrap().path();
1640             {
1641                 let n = f.file_stem().unwrap();
1642                 check!(check!(File::open(&f)).read(&mut mem));
1643                 let read_str = str::from_utf8(&mem).unwrap();
1644                 let expected = format!("{}{}", prefix, n.to_str().unwrap());
1645                 assert_eq!(expected, read_str);
1646             }
1647             check!(fs::remove_file(&f));
1648         }
1649         check!(fs::remove_dir(dir));
1650     }
1651
1652     #[test]
1653     fn file_test_walk_dir() {
1654         let tmpdir = tmpdir();
1655         let dir = &tmpdir.join("walk_dir");
1656         check!(fs::create_dir(dir));
1657
1658         let dir1 = &dir.join("01/02/03");
1659         check!(fs::create_dir_all(dir1));
1660         check!(File::create(&dir1.join("04")));
1661
1662         let dir2 = &dir.join("11/12/13");
1663         check!(fs::create_dir_all(dir2));
1664         check!(File::create(&dir2.join("14")));
1665
1666         let files = check!(fs::walk_dir(dir));
1667         let mut cur = [0; 2];
1668         for f in files {
1669             let f = f.unwrap().path();
1670             let stem = f.file_stem().unwrap().to_str().unwrap();
1671             let root = stem.as_bytes()[0] - b'0';
1672             let name = stem.as_bytes()[1] - b'0';
1673             assert!(cur[root as usize] < name);
1674             cur[root as usize] = name;
1675         }
1676
1677         check!(fs::remove_dir_all(dir));
1678     }
1679
1680     #[test]
1681     fn mkdir_path_already_exists_error() {
1682         let tmpdir = tmpdir();
1683         let dir = &tmpdir.join("mkdir_error_twice");
1684         check!(fs::create_dir(dir));
1685         let e = fs::create_dir(dir).err().unwrap();
1686         assert_eq!(e.kind(), ErrorKind::AlreadyExists);
1687     }
1688
1689     #[test]
1690     fn recursive_mkdir() {
1691         let tmpdir = tmpdir();
1692         let dir = tmpdir.join("d1/d2");
1693         check!(fs::create_dir_all(&dir));
1694         assert!(dir.is_dir())
1695     }
1696
1697     #[test]
1698     fn recursive_mkdir_failure() {
1699         let tmpdir = tmpdir();
1700         let dir = tmpdir.join("d1");
1701         let file = dir.join("f1");
1702
1703         check!(fs::create_dir_all(&dir));
1704         check!(File::create(&file));
1705
1706         let result = fs::create_dir_all(&file);
1707
1708         assert!(result.is_err());
1709         // error!(result, "couldn't recursively mkdir");
1710         // error!(result, "couldn't create directory");
1711         // error!(result, "mode=0700");
1712         // error!(result, format!("path={}", file.display()));
1713     }
1714
1715     #[test]
1716     fn recursive_mkdir_slash() {
1717         check!(fs::create_dir_all(&Path2::new("/")));
1718     }
1719
1720     // FIXME(#12795) depends on lstat to work on windows
1721     #[cfg(not(windows))]
1722     #[test]
1723     fn recursive_rmdir() {
1724         let tmpdir = tmpdir();
1725         let d1 = tmpdir.join("d1");
1726         let dt = d1.join("t");
1727         let dtt = dt.join("t");
1728         let d2 = tmpdir.join("d2");
1729         let canary = d2.join("do_not_delete");
1730         check!(fs::create_dir_all(&dtt));
1731         check!(fs::create_dir_all(&d2));
1732         check!(check!(File::create(&canary)).write(b"foo"));
1733         check!(fs::soft_link(&d2, &dt.join("d2")));
1734         check!(fs::remove_dir_all(&d1));
1735
1736         assert!(!d1.is_dir());
1737         assert!(canary.exists());
1738     }
1739
1740     #[test]
1741     fn unicode_path_is_dir() {
1742         assert!(Path2::new(".").is_dir());
1743         assert!(!Path2::new("test/stdtest/fs.rs").is_dir());
1744
1745         let tmpdir = tmpdir();
1746
1747         let mut dirpath = tmpdir.path().to_path_buf();
1748         dirpath.push(&format!("test-가一ー你好"));
1749         check!(fs::create_dir(&dirpath));
1750         assert!(dirpath.is_dir());
1751
1752         let mut filepath = dirpath;
1753         filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
1754         check!(File::create(&filepath)); // ignore return; touch only
1755         assert!(!filepath.is_dir());
1756         assert!(filepath.exists());
1757     }
1758
1759     #[test]
1760     fn unicode_path_exists() {
1761         assert!(Path2::new(".").exists());
1762         assert!(!Path2::new("test/nonexistent-bogus-path").exists());
1763
1764         let tmpdir = tmpdir();
1765         let unicode = tmpdir.path();
1766         let unicode = unicode.join(&format!("test-각丁ー再见"));
1767         check!(fs::create_dir(&unicode));
1768         assert!(unicode.exists());
1769         assert!(!Path2::new("test/unicode-bogus-path-각丁ー再见").exists());
1770     }
1771
1772     #[test]
1773     fn copy_file_does_not_exist() {
1774         let from = Path2::new("test/nonexistent-bogus-path");
1775         let to = Path2::new("test/other-bogus-path");
1776
1777         match fs::copy(&from, &to) {
1778             Ok(..) => panic!(),
1779             Err(..) => {
1780                 assert!(!from.exists());
1781                 assert!(!to.exists());
1782             }
1783         }
1784     }
1785
1786     #[test]
1787     fn copy_file_ok() {
1788         let tmpdir = tmpdir();
1789         let input = tmpdir.join("in.txt");
1790         let out = tmpdir.join("out.txt");
1791
1792         check!(check!(File::create(&input)).write(b"hello"));
1793         check!(fs::copy(&input, &out));
1794         let mut v = Vec::new();
1795         check!(check!(File::open(&out)).read_to_end(&mut v));
1796         assert_eq!(v, b"hello");
1797
1798         assert_eq!(check!(input.metadata()).permissions(),
1799                    check!(out.metadata()).permissions());
1800     }
1801
1802     #[test]
1803     fn copy_file_dst_dir() {
1804         let tmpdir = tmpdir();
1805         let out = tmpdir.join("out");
1806
1807         check!(File::create(&out));
1808         match fs::copy(&*out, tmpdir.path()) {
1809             Ok(..) => panic!(), Err(..) => {}
1810         }
1811     }
1812
1813     #[test]
1814     fn copy_file_dst_exists() {
1815         let tmpdir = tmpdir();
1816         let input = tmpdir.join("in");
1817         let output = tmpdir.join("out");
1818
1819         check!(check!(File::create(&input)).write("foo".as_bytes()));
1820         check!(check!(File::create(&output)).write("bar".as_bytes()));
1821         check!(fs::copy(&input, &output));
1822
1823         let mut v = Vec::new();
1824         check!(check!(File::open(&output)).read_to_end(&mut v));
1825         assert_eq!(v, b"foo".to_vec());
1826     }
1827
1828     #[test]
1829     fn copy_file_src_dir() {
1830         let tmpdir = tmpdir();
1831         let out = tmpdir.join("out");
1832
1833         match fs::copy(tmpdir.path(), &out) {
1834             Ok(..) => panic!(), Err(..) => {}
1835         }
1836         assert!(!out.exists());
1837     }
1838
1839     #[test]
1840     fn copy_file_preserves_perm_bits() {
1841         let tmpdir = tmpdir();
1842         let input = tmpdir.join("in.txt");
1843         let out = tmpdir.join("out.txt");
1844
1845         let attr = check!(check!(File::create(&input)).metadata());
1846         let mut p = attr.permissions();
1847         p.set_readonly(true);
1848         check!(fs::set_permissions(&input, p));
1849         check!(fs::copy(&input, &out));
1850         assert!(check!(out.metadata()).permissions().readonly());
1851         check!(fs::set_permissions(&input, attr.permissions()));
1852         check!(fs::set_permissions(&out, attr.permissions()));
1853     }
1854
1855     #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
1856     #[test]
1857     fn symlinks_work() {
1858         let tmpdir = tmpdir();
1859         let input = tmpdir.join("in.txt");
1860         let out = tmpdir.join("out.txt");
1861
1862         check!(check!(File::create(&input)).write("foobar".as_bytes()));
1863         check!(fs::soft_link(&input, &out));
1864         // if cfg!(not(windows)) {
1865         //     assert_eq!(check!(lstat(&out)).kind, FileType::Symlink);
1866         //     assert_eq!(check!(out.lstat()).kind, FileType::Symlink);
1867         // }
1868         assert_eq!(check!(fs::metadata(&out)).len(),
1869                    check!(fs::metadata(&input)).len());
1870         let mut v = Vec::new();
1871         check!(check!(File::open(&out)).read_to_end(&mut v));
1872         assert_eq!(v, b"foobar".to_vec());
1873     }
1874
1875     #[cfg(not(windows))] // apparently windows doesn't like symlinks
1876     #[test]
1877     fn symlink_noexist() {
1878         let tmpdir = tmpdir();
1879         // symlinks can point to things that don't exist
1880         check!(fs::soft_link(&tmpdir.join("foo"), &tmpdir.join("bar")));
1881         assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))),
1882                    tmpdir.join("foo"));
1883     }
1884
1885     #[test]
1886     fn readlink_not_symlink() {
1887         let tmpdir = tmpdir();
1888         match fs::read_link(tmpdir.path()) {
1889             Ok(..) => panic!("wanted a failure"),
1890             Err(..) => {}
1891         }
1892     }
1893
1894     #[test]
1895     fn links_work() {
1896         let tmpdir = tmpdir();
1897         let input = tmpdir.join("in.txt");
1898         let out = tmpdir.join("out.txt");
1899
1900         check!(check!(File::create(&input)).write("foobar".as_bytes()));
1901         check!(fs::hard_link(&input, &out));
1902         assert_eq!(check!(fs::metadata(&out)).len(),
1903                    check!(fs::metadata(&input)).len());
1904         assert_eq!(check!(fs::metadata(&out)).len(),
1905                    check!(input.metadata()).len());
1906         let mut v = Vec::new();
1907         check!(check!(File::open(&out)).read_to_end(&mut v));
1908         assert_eq!(v, b"foobar".to_vec());
1909
1910         // can't link to yourself
1911         match fs::hard_link(&input, &input) {
1912             Ok(..) => panic!("wanted a failure"),
1913             Err(..) => {}
1914         }
1915         // can't link to something that doesn't exist
1916         match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
1917             Ok(..) => panic!("wanted a failure"),
1918             Err(..) => {}
1919         }
1920     }
1921
1922     #[test]
1923     fn chmod_works() {
1924         let tmpdir = tmpdir();
1925         let file = tmpdir.join("in.txt");
1926
1927         check!(File::create(&file));
1928         let attr = check!(fs::metadata(&file));
1929         assert!(!attr.permissions().readonly());
1930         let mut p = attr.permissions();
1931         p.set_readonly(true);
1932         check!(fs::set_permissions(&file, p.clone()));
1933         let attr = check!(fs::metadata(&file));
1934         assert!(attr.permissions().readonly());
1935
1936         match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
1937             Ok(..) => panic!("wanted an error"),
1938             Err(..) => {}
1939         }
1940
1941         p.set_readonly(false);
1942         check!(fs::set_permissions(&file, p));
1943     }
1944
1945     #[test]
1946     fn sync_doesnt_kill_anything() {
1947         let tmpdir = tmpdir();
1948         let path = tmpdir.join("in.txt");
1949
1950         let mut file = check!(File::create(&path));
1951         check!(file.sync_all());
1952         check!(file.sync_data());
1953         check!(file.write(b"foo"));
1954         check!(file.sync_all());
1955         check!(file.sync_data());
1956     }
1957
1958     #[test]
1959     fn truncate_works() {
1960         let tmpdir = tmpdir();
1961         let path = tmpdir.join("in.txt");
1962
1963         let mut file = check!(File::create(&path));
1964         check!(file.write(b"foo"));
1965         check!(file.sync_all());
1966
1967         // Do some simple things with truncation
1968         assert_eq!(check!(file.metadata()).len(), 3);
1969         check!(file.set_len(10));
1970         assert_eq!(check!(file.metadata()).len(), 10);
1971         check!(file.write(b"bar"));
1972         check!(file.sync_all());
1973         assert_eq!(check!(file.metadata()).len(), 10);
1974
1975         let mut v = Vec::new();
1976         check!(check!(File::open(&path)).read_to_end(&mut v));
1977         assert_eq!(v, b"foobar\0\0\0\0".to_vec());
1978
1979         // Truncate to a smaller length, don't seek, and then write something.
1980         // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
1981         // past the end of the file).
1982         check!(file.set_len(2));
1983         assert_eq!(check!(file.metadata()).len(), 2);
1984         check!(file.write(b"wut"));
1985         check!(file.sync_all());
1986         assert_eq!(check!(file.metadata()).len(), 9);
1987         let mut v = Vec::new();
1988         check!(check!(File::open(&path)).read_to_end(&mut v));
1989         assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
1990     }
1991
1992     #[test]
1993     fn open_flavors() {
1994         use fs::OpenOptions as OO;
1995         fn c<T: Clone>(t: &T) -> T { t.clone() }
1996
1997         let tmpdir = tmpdir();
1998
1999         let mut r = OO::new(); r.read(true);
2000         let mut w = OO::new(); w.write(true);
2001         let mut rw = OO::new(); rw.write(true).read(true);
2002
2003         match r.open(&tmpdir.join("a")) {
2004             Ok(..) => panic!(), Err(..) => {}
2005         }
2006
2007         // Perform each one twice to make sure that it succeeds the second time
2008         // (where the file exists)
2009         check!(c(&w).create(true).open(&tmpdir.join("b")));
2010         assert!(tmpdir.join("b").exists());
2011         check!(c(&w).create(true).open(&tmpdir.join("b")));
2012         check!(w.open(&tmpdir.join("b")));
2013
2014         check!(c(&rw).create(true).open(&tmpdir.join("c")));
2015         assert!(tmpdir.join("c").exists());
2016         check!(c(&rw).create(true).open(&tmpdir.join("c")));
2017         check!(rw.open(&tmpdir.join("c")));
2018
2019         check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2020         assert!(tmpdir.join("d").exists());
2021         check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
2022         check!(c(&w).append(true).open(&tmpdir.join("d")));
2023
2024         check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2025         assert!(tmpdir.join("e").exists());
2026         check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
2027         check!(c(&rw).append(true).open(&tmpdir.join("e")));
2028
2029         check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2030         assert!(tmpdir.join("f").exists());
2031         check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
2032         check!(c(&w).truncate(true).open(&tmpdir.join("f")));
2033
2034         check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2035         assert!(tmpdir.join("g").exists());
2036         check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
2037         check!(c(&rw).truncate(true).open(&tmpdir.join("g")));
2038
2039         check!(check!(File::create(&tmpdir.join("h"))).write("foo".as_bytes()));
2040         check!(r.open(&tmpdir.join("h")));
2041         {
2042             let mut f = check!(r.open(&tmpdir.join("h")));
2043             assert!(f.write("wut".as_bytes()).is_err());
2044         }
2045         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2046         {
2047             let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
2048             check!(f.write("bar".as_bytes()));
2049         }
2050         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
2051         {
2052             let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
2053             check!(f.write("bar".as_bytes()));
2054         }
2055         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2056     }
2057
2058     #[test]
2059     fn utime() {
2060         let tmpdir = tmpdir();
2061         let path = tmpdir.join("a");
2062         check!(File::create(&path));
2063         // These numbers have to be bigger than the time in the day to account
2064         // for timezones Windows in particular will fail in certain timezones
2065         // with small enough values
2066         check!(fs::set_file_times(&path, 100000, 200000));
2067         assert_eq!(check!(path.metadata()).accessed(), 100000);
2068         assert_eq!(check!(path.metadata()).modified(), 200000);
2069     }
2070
2071     #[test]
2072     fn utime_noexist() {
2073         let tmpdir = tmpdir();
2074
2075         match fs::set_file_times(&tmpdir.join("a"), 100, 200) {
2076             Ok(..) => panic!(),
2077             Err(..) => {}
2078         }
2079     }
2080
2081     #[test]
2082     fn binary_file() {
2083         let mut bytes = [0; 1024];
2084         StdRng::new().unwrap().fill_bytes(&mut bytes);
2085
2086         let tmpdir = tmpdir();
2087
2088         check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
2089         let mut v = Vec::new();
2090         check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
2091         assert!(v == &bytes[..]);
2092     }
2093
2094     #[test]
2095     #[cfg(not(windows))]
2096     fn unlink_readonly() {
2097         let tmpdir = tmpdir();
2098         let path = tmpdir.join("file");
2099         check!(File::create(&path));
2100         let mut perm = check!(fs::metadata(&path)).permissions();
2101         perm.set_readonly(true);
2102         check!(fs::set_permissions(&path, perm));
2103         check!(fs::remove_file(&path));
2104     }
2105
2106     #[test]
2107     fn mkdir_trailing_slash() {
2108         let tmpdir = tmpdir();
2109         let path = tmpdir.join("file");
2110         check!(fs::create_dir_all(&path.join("a/")));
2111     }
2112
2113     #[test]
2114     #[cfg(not(windows))]
2115     fn realpath_works() {
2116         let tmpdir = tmpdir();
2117         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2118         let file = tmpdir.join("test");
2119         let dir = tmpdir.join("test2");
2120         let link = dir.join("link");
2121         let linkdir = tmpdir.join("test3");
2122
2123         File::create(&file).unwrap();
2124         fs::create_dir(&dir).unwrap();
2125         fs::soft_link(&file, &link).unwrap();
2126         fs::soft_link(&dir, &linkdir).unwrap();
2127
2128         assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
2129
2130         assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
2131         assert_eq!(fs::canonicalize(&file).unwrap(), file);
2132         assert_eq!(fs::canonicalize(&link).unwrap(), file);
2133         assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
2134         assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
2135     }
2136
2137     #[test]
2138     #[cfg(not(windows))]
2139     fn realpath_works_tricky() {
2140         let tmpdir = tmpdir();
2141         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2142
2143         let a = tmpdir.join("a");
2144         let b = a.join("b");
2145         let c = b.join("c");
2146         let d = a.join("d");
2147         let e = d.join("e");
2148         let f = a.join("f");
2149
2150         fs::create_dir_all(&b).unwrap();
2151         fs::create_dir_all(&d).unwrap();
2152         File::create(&f).unwrap();
2153         fs::soft_link("../d/e", &c).unwrap();
2154         fs::soft_link("../f", &e).unwrap();
2155
2156         assert_eq!(fs::canonicalize(&c).unwrap(), f);
2157         assert_eq!(fs::canonicalize(&e).unwrap(), f);
2158     }
2159
2160     #[test]
2161     fn dir_entry_methods() {
2162         let tmpdir = tmpdir();
2163
2164         fs::create_dir_all(&tmpdir.join("a")).unwrap();
2165         File::create(&tmpdir.join("b")).unwrap();
2166
2167         for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
2168             let fname = file.file_name();
2169             match fname.to_str() {
2170                 Some("a") => {
2171                     assert!(file.file_type().unwrap().is_dir());
2172                     assert!(file.metadata().unwrap().is_dir());
2173                 }
2174                 Some("b") => {
2175                     assert!(file.file_type().unwrap().is_file());
2176                     assert!(file.metadata().unwrap().is_file());
2177                 }
2178                 f => panic!("unknown file name: {:?}", f),
2179             }
2180         }
2181     }
2182 }