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