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