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