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