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