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