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