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