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