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