]> git.lizzy.rs Git - rust.git/blob - src/libstd/fs.rs
Rollup merge of #58440 - gnzlbg:v6, r=japaric
[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 /// Creates 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     /// Creates 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     /// Creates 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 `true` if 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 `true` if 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 `true` if 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     /// [`fs::set_permissions`]: fn.set_permissions.html
1127     ///
1128     /// # Examples
1129     ///
1130     /// ```no_run
1131     /// use std::fs::File;
1132     ///
1133     /// fn main() -> std::io::Result<()> {
1134     ///     let f = File::create("foo.txt")?;
1135     ///     let metadata = f.metadata()?;
1136     ///     let mut permissions = metadata.permissions();
1137     ///
1138     ///     permissions.set_readonly(true);
1139     ///
1140     ///     // filesystem doesn't change
1141     ///     assert_eq!(false, metadata.permissions().readonly());
1142     ///
1143     ///     // just this particular `permissions`.
1144     ///     assert_eq!(true, permissions.readonly());
1145     ///     Ok(())
1146     /// }
1147     /// ```
1148     #[stable(feature = "rust1", since = "1.0.0")]
1149     pub fn set_readonly(&mut self, readonly: bool) {
1150         self.0.set_readonly(readonly)
1151     }
1152 }
1153
1154 impl FileType {
1155     /// Tests whether this file type represents a directory. The
1156     /// result is mutually exclusive to the results of
1157     /// [`is_file`] and [`is_symlink`]; only zero or one of these
1158     /// tests may pass.
1159     ///
1160     /// [`is_file`]: struct.FileType.html#method.is_file
1161     /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1162     ///
1163     /// # Examples
1164     ///
1165     /// ```no_run
1166     /// fn main() -> std::io::Result<()> {
1167     ///     use std::fs;
1168     ///
1169     ///     let metadata = fs::metadata("foo.txt")?;
1170     ///     let file_type = metadata.file_type();
1171     ///
1172     ///     assert_eq!(file_type.is_dir(), false);
1173     ///     Ok(())
1174     /// }
1175     /// ```
1176     #[stable(feature = "file_type", since = "1.1.0")]
1177     pub fn is_dir(&self) -> bool { self.0.is_dir() }
1178
1179     /// Tests whether this file type represents a regular file.
1180     /// The result is  mutually exclusive to the results of
1181     /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1182     /// tests may pass.
1183     ///
1184     /// [`is_dir`]: struct.FileType.html#method.is_dir
1185     /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1186     ///
1187     /// # Examples
1188     ///
1189     /// ```no_run
1190     /// fn main() -> std::io::Result<()> {
1191     ///     use std::fs;
1192     ///
1193     ///     let metadata = fs::metadata("foo.txt")?;
1194     ///     let file_type = metadata.file_type();
1195     ///
1196     ///     assert_eq!(file_type.is_file(), true);
1197     ///     Ok(())
1198     /// }
1199     /// ```
1200     #[stable(feature = "file_type", since = "1.1.0")]
1201     pub fn is_file(&self) -> bool { self.0.is_file() }
1202
1203     /// Tests whether this file type represents a symbolic link.
1204     /// The result is mutually exclusive to the results of
1205     /// [`is_dir`] and [`is_file`]; only zero or one of these
1206     /// tests may pass.
1207     ///
1208     /// The underlying [`Metadata`] struct needs to be retrieved
1209     /// with the [`fs::symlink_metadata`] function and not the
1210     /// [`fs::metadata`] function. The [`fs::metadata`] function
1211     /// follows symbolic links, so [`is_symlink`] would always
1212     /// return `false` for the target file.
1213     ///
1214     /// [`Metadata`]: struct.Metadata.html
1215     /// [`fs::metadata`]: fn.metadata.html
1216     /// [`fs::symlink_metadata`]: fn.symlink_metadata.html
1217     /// [`is_dir`]: struct.FileType.html#method.is_dir
1218     /// [`is_file`]: struct.FileType.html#method.is_file
1219     /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1220     ///
1221     /// # Examples
1222     ///
1223     /// ```no_run
1224     /// use std::fs;
1225     ///
1226     /// fn main() -> std::io::Result<()> {
1227     ///     let metadata = fs::symlink_metadata("foo.txt")?;
1228     ///     let file_type = metadata.file_type();
1229     ///
1230     ///     assert_eq!(file_type.is_symlink(), false);
1231     ///     Ok(())
1232     /// }
1233     /// ```
1234     #[stable(feature = "file_type", since = "1.1.0")]
1235     pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
1236 }
1237
1238 impl AsInner<fs_imp::FileType> for FileType {
1239     fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
1240 }
1241
1242 impl FromInner<fs_imp::FilePermissions> for Permissions {
1243     fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1244         Permissions(f)
1245     }
1246 }
1247
1248 impl AsInner<fs_imp::FilePermissions> for Permissions {
1249     fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
1250 }
1251
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 impl Iterator for ReadDir {
1254     type Item = io::Result<DirEntry>;
1255
1256     fn next(&mut self) -> Option<io::Result<DirEntry>> {
1257         self.0.next().map(|entry| entry.map(DirEntry))
1258     }
1259 }
1260
1261 impl DirEntry {
1262     /// Returns the full path to the file that this entry represents.
1263     ///
1264     /// The full path is created by joining the original path to `read_dir`
1265     /// with the filename of this entry.
1266     ///
1267     /// # Examples
1268     ///
1269     /// ```no_run
1270     /// use std::fs;
1271     ///
1272     /// fn main() -> std::io::Result<()> {
1273     ///     for entry in fs::read_dir(".")? {
1274     ///         let dir = entry?;
1275     ///         println!("{:?}", dir.path());
1276     ///     }
1277     ///     Ok(())
1278     /// }
1279     /// ```
1280     ///
1281     /// This prints output like:
1282     ///
1283     /// ```text
1284     /// "./whatever.txt"
1285     /// "./foo.html"
1286     /// "./hello_world.rs"
1287     /// ```
1288     ///
1289     /// The exact text, of course, depends on what files you have in `.`.
1290     #[stable(feature = "rust1", since = "1.0.0")]
1291     pub fn path(&self) -> PathBuf { self.0.path() }
1292
1293     /// Returns the metadata for the file that this entry points at.
1294     ///
1295     /// This function will not traverse symlinks if this entry points at a
1296     /// symlink.
1297     ///
1298     /// # Platform-specific behavior
1299     ///
1300     /// On Windows this function is cheap to call (no extra system calls
1301     /// needed), but on Unix platforms this function is the equivalent of
1302     /// calling `symlink_metadata` on the path.
1303     ///
1304     /// # Examples
1305     ///
1306     /// ```
1307     /// use std::fs;
1308     ///
1309     /// if let Ok(entries) = fs::read_dir(".") {
1310     ///     for entry in entries {
1311     ///         if let Ok(entry) = entry {
1312     ///             // Here, `entry` is a `DirEntry`.
1313     ///             if let Ok(metadata) = entry.metadata() {
1314     ///                 // Now let's show our entry's permissions!
1315     ///                 println!("{:?}: {:?}", entry.path(), metadata.permissions());
1316     ///             } else {
1317     ///                 println!("Couldn't get metadata for {:?}", entry.path());
1318     ///             }
1319     ///         }
1320     ///     }
1321     /// }
1322     /// ```
1323     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1324     pub fn metadata(&self) -> io::Result<Metadata> {
1325         self.0.metadata().map(Metadata)
1326     }
1327
1328     /// Returns the file type for the file that this entry points at.
1329     ///
1330     /// This function will not traverse symlinks if this entry points at a
1331     /// symlink.
1332     ///
1333     /// # Platform-specific behavior
1334     ///
1335     /// On Windows and most Unix platforms this function is free (no extra
1336     /// system calls needed), but some Unix platforms may require the equivalent
1337     /// call to `symlink_metadata` to learn about the target file type.
1338     ///
1339     /// # Examples
1340     ///
1341     /// ```
1342     /// use std::fs;
1343     ///
1344     /// if let Ok(entries) = fs::read_dir(".") {
1345     ///     for entry in entries {
1346     ///         if let Ok(entry) = entry {
1347     ///             // Here, `entry` is a `DirEntry`.
1348     ///             if let Ok(file_type) = entry.file_type() {
1349     ///                 // Now let's show our entry's file type!
1350     ///                 println!("{:?}: {:?}", entry.path(), file_type);
1351     ///             } else {
1352     ///                 println!("Couldn't get file type for {:?}", entry.path());
1353     ///             }
1354     ///         }
1355     ///     }
1356     /// }
1357     /// ```
1358     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1359     pub fn file_type(&self) -> io::Result<FileType> {
1360         self.0.file_type().map(FileType)
1361     }
1362
1363     /// Returns the bare file name of this directory entry without any other
1364     /// leading path component.
1365     ///
1366     /// # Examples
1367     ///
1368     /// ```
1369     /// use std::fs;
1370     ///
1371     /// if let Ok(entries) = fs::read_dir(".") {
1372     ///     for entry in entries {
1373     ///         if let Ok(entry) = entry {
1374     ///             // Here, `entry` is a `DirEntry`.
1375     ///             println!("{:?}", entry.file_name());
1376     ///         }
1377     ///     }
1378     /// }
1379     /// ```
1380     #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1381     pub fn file_name(&self) -> OsString {
1382         self.0.file_name()
1383     }
1384 }
1385
1386 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1387 impl fmt::Debug for DirEntry {
1388     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1389         f.debug_tuple("DirEntry")
1390             .field(&self.path())
1391             .finish()
1392     }
1393 }
1394
1395 impl AsInner<fs_imp::DirEntry> for DirEntry {
1396     fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
1397 }
1398
1399 /// Removes a file from the filesystem.
1400 ///
1401 /// Note that there is no
1402 /// guarantee that the file is immediately deleted (e.g., depending on
1403 /// platform, other open file descriptors may prevent immediate removal).
1404 ///
1405 /// # Platform-specific behavior
1406 ///
1407 /// This function currently corresponds to the `unlink` function on Unix
1408 /// and the `DeleteFile` function on Windows.
1409 /// Note that, this [may change in the future][changes].
1410 ///
1411 /// [changes]: ../io/index.html#platform-specific-behavior
1412 ///
1413 /// # Errors
1414 ///
1415 /// This function will return an error in the following situations, but is not
1416 /// limited to just these cases:
1417 ///
1418 /// * `path` points to a directory.
1419 /// * The user lacks permissions to remove the file.
1420 ///
1421 /// # Examples
1422 ///
1423 /// ```no_run
1424 /// use std::fs;
1425 ///
1426 /// fn main() -> std::io::Result<()> {
1427 ///     fs::remove_file("a.txt")?;
1428 ///     Ok(())
1429 /// }
1430 /// ```
1431 #[stable(feature = "rust1", since = "1.0.0")]
1432 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1433     fs_imp::unlink(path.as_ref())
1434 }
1435
1436 /// Given a path, query the file system to get information about a file,
1437 /// directory, etc.
1438 ///
1439 /// This function will traverse symbolic links to query information about the
1440 /// destination file.
1441 ///
1442 /// # Platform-specific behavior
1443 ///
1444 /// This function currently corresponds to the `stat` function on Unix
1445 /// and the `GetFileAttributesEx` function on Windows.
1446 /// Note that, this [may change in the future][changes].
1447 ///
1448 /// [changes]: ../io/index.html#platform-specific-behavior
1449 ///
1450 /// # Errors
1451 ///
1452 /// This function will return an error in the following situations, but is not
1453 /// limited to just these cases:
1454 ///
1455 /// * The user lacks permissions to perform `metadata` call on `path`.
1456 /// * `path` does not exist.
1457 ///
1458 /// # Examples
1459 ///
1460 /// ```rust,no_run
1461 /// use std::fs;
1462 ///
1463 /// fn main() -> std::io::Result<()> {
1464 ///     let attr = fs::metadata("/some/file/path.txt")?;
1465 ///     // inspect attr ...
1466 ///     Ok(())
1467 /// }
1468 /// ```
1469 #[stable(feature = "rust1", since = "1.0.0")]
1470 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1471     fs_imp::stat(path.as_ref()).map(Metadata)
1472 }
1473
1474 /// Query the metadata about a file without following symlinks.
1475 ///
1476 /// # Platform-specific behavior
1477 ///
1478 /// This function currently corresponds to the `lstat` function on Unix
1479 /// and the `GetFileAttributesEx` function on Windows.
1480 /// Note that, this [may change in the future][changes].
1481 ///
1482 /// [changes]: ../io/index.html#platform-specific-behavior
1483 ///
1484 /// # Errors
1485 ///
1486 /// This function will return an error in the following situations, but is not
1487 /// limited to just these cases:
1488 ///
1489 /// * The user lacks permissions to perform `metadata` call on `path`.
1490 /// * `path` does not exist.
1491 ///
1492 /// # Examples
1493 ///
1494 /// ```rust,no_run
1495 /// use std::fs;
1496 ///
1497 /// fn main() -> std::io::Result<()> {
1498 ///     let attr = fs::symlink_metadata("/some/file/path.txt")?;
1499 ///     // inspect attr ...
1500 ///     Ok(())
1501 /// }
1502 /// ```
1503 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1504 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1505     fs_imp::lstat(path.as_ref()).map(Metadata)
1506 }
1507
1508 /// Rename a file or directory to a new name, replacing the original file if
1509 /// `to` already exists.
1510 ///
1511 /// This will not work if the new name is on a different mount point.
1512 ///
1513 /// # Platform-specific behavior
1514 ///
1515 /// This function currently corresponds to the `rename` function on Unix
1516 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1517 ///
1518 /// Because of this, the behavior when both `from` and `to` exist differs. On
1519 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1520 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1521 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1522 ///
1523 /// Note that, this [may change in the future][changes].
1524 ///
1525 /// [changes]: ../io/index.html#platform-specific-behavior
1526 ///
1527 /// # Errors
1528 ///
1529 /// This function will return an error in the following situations, but is not
1530 /// limited to just these cases:
1531 ///
1532 /// * `from` does not exist.
1533 /// * The user lacks permissions to view contents.
1534 /// * `from` and `to` are on separate filesystems.
1535 ///
1536 /// # Examples
1537 ///
1538 /// ```no_run
1539 /// use std::fs;
1540 ///
1541 /// fn main() -> std::io::Result<()> {
1542 ///     fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1543 ///     Ok(())
1544 /// }
1545 /// ```
1546 #[stable(feature = "rust1", since = "1.0.0")]
1547 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1548     fs_imp::rename(from.as_ref(), to.as_ref())
1549 }
1550
1551 /// Copies the contents of one file to another. This function will also
1552 /// copy the permission bits of the original file to the destination file.
1553 ///
1554 /// This function will **overwrite** the contents of `to`.
1555 ///
1556 /// Note that if `from` and `to` both point to the same file, then the file
1557 /// will likely get truncated by this operation.
1558 ///
1559 /// On success, the total number of bytes copied is returned and it is equal to
1560 /// the length of the `to` file as reported by `metadata`.
1561 ///
1562 /// If you’re wanting to copy the contents of one file to another and you’re
1563 /// working with [`File`]s, see the [`io::copy`] function.
1564 ///
1565 /// [`io::copy`]: ../io/fn.copy.html
1566 /// [`File`]: ./struct.File.html
1567 ///
1568 /// # Platform-specific behavior
1569 ///
1570 /// This function currently corresponds to the `open` function in Unix
1571 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1572 /// `O_CLOEXEC` is set for returned file descriptors.
1573 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1574 /// NTFS streams are copied but only the size of the main stream is returned by
1575 /// this function.
1576 /// Note that, this [may change in the future][changes].
1577 ///
1578 /// [changes]: ../io/index.html#platform-specific-behavior
1579 ///
1580 /// # Errors
1581 ///
1582 /// This function will return an error in the following situations, but is not
1583 /// limited to just these cases:
1584 ///
1585 /// * The `from` path is not a file.
1586 /// * The `from` file does not exist.
1587 /// * The current process does not have the permission rights to access
1588 ///   `from` or write `to`.
1589 ///
1590 /// # Examples
1591 ///
1592 /// ```no_run
1593 /// use std::fs;
1594 ///
1595 /// fn main() -> std::io::Result<()> {
1596 ///     fs::copy("foo.txt", "bar.txt")?;  // Copy foo.txt to bar.txt
1597 ///     Ok(())
1598 /// }
1599 /// ```
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1602     fs_imp::copy(from.as_ref(), to.as_ref())
1603 }
1604
1605 /// Creates a new hard link on the filesystem.
1606 ///
1607 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1608 /// often require these two paths to both be located on the same filesystem.
1609 ///
1610 /// # Platform-specific behavior
1611 ///
1612 /// This function currently corresponds to the `link` function on Unix
1613 /// and the `CreateHardLink` function on Windows.
1614 /// Note that, this [may change in the future][changes].
1615 ///
1616 /// [changes]: ../io/index.html#platform-specific-behavior
1617 ///
1618 /// # Errors
1619 ///
1620 /// This function will return an error in the following situations, but is not
1621 /// limited to just these cases:
1622 ///
1623 /// * The `src` path is not a file or doesn't exist.
1624 ///
1625 /// # Examples
1626 ///
1627 /// ```no_run
1628 /// use std::fs;
1629 ///
1630 /// fn main() -> std::io::Result<()> {
1631 ///     fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1632 ///     Ok(())
1633 /// }
1634 /// ```
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1637     fs_imp::link(src.as_ref(), dst.as_ref())
1638 }
1639
1640 /// Creates a new symbolic link on the filesystem.
1641 ///
1642 /// The `dst` path will be a symbolic link pointing to the `src` path.
1643 /// On Windows, this will be a file symlink, not a directory symlink;
1644 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1645 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1646 /// used instead to make the intent explicit.
1647 ///
1648 /// [`std::os::unix::fs::symlink`]: ../os/unix/fs/fn.symlink.html
1649 /// [`std::os::windows::fs::symlink_file`]: ../os/windows/fs/fn.symlink_file.html
1650 /// [`symlink_dir`]: ../os/windows/fs/fn.symlink_dir.html
1651 ///
1652 ///
1653 /// # Examples
1654 ///
1655 /// ```no_run
1656 /// use std::fs;
1657 ///
1658 /// fn main() -> std::io::Result<()> {
1659 ///     fs::soft_link("a.txt", "b.txt")?;
1660 ///     Ok(())
1661 /// }
1662 /// ```
1663 #[stable(feature = "rust1", since = "1.0.0")]
1664 #[rustc_deprecated(since = "1.1.0",
1665              reason = "replaced with std::os::unix::fs::symlink and \
1666                        std::os::windows::fs::{symlink_file, symlink_dir}")]
1667 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1668     fs_imp::symlink(src.as_ref(), dst.as_ref())
1669 }
1670
1671 /// Reads a symbolic link, returning the file that the link points to.
1672 ///
1673 /// # Platform-specific behavior
1674 ///
1675 /// This function currently corresponds to the `readlink` function on Unix
1676 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1677 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1678 /// Note that, this [may change in the future][changes].
1679 ///
1680 /// [changes]: ../io/index.html#platform-specific-behavior
1681 ///
1682 /// # Errors
1683 ///
1684 /// This function will return an error in the following situations, but is not
1685 /// limited to just these cases:
1686 ///
1687 /// * `path` is not a symbolic link.
1688 /// * `path` does not exist.
1689 ///
1690 /// # Examples
1691 ///
1692 /// ```no_run
1693 /// use std::fs;
1694 ///
1695 /// fn main() -> std::io::Result<()> {
1696 ///     let path = fs::read_link("a.txt")?;
1697 ///     Ok(())
1698 /// }
1699 /// ```
1700 #[stable(feature = "rust1", since = "1.0.0")]
1701 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1702     fs_imp::readlink(path.as_ref())
1703 }
1704
1705 /// Returns the canonical, absolute form of a path with all intermediate
1706 /// components normalized and symbolic links resolved.
1707 ///
1708 /// # Platform-specific behavior
1709 ///
1710 /// This function currently corresponds to the `realpath` function on Unix
1711 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1712 /// Note that, this [may change in the future][changes].
1713 ///
1714 /// On Windows, this converts the path to use [extended length path][path]
1715 /// syntax, which allows your program to use longer path names, but means you
1716 /// can only join backslash-delimited paths to it, and it may be incompatible
1717 /// with other applications (if passed to the application on the command-line,
1718 /// or written to a file another application may read).
1719 ///
1720 /// [changes]: ../io/index.html#platform-specific-behavior
1721 /// [path]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
1722 ///
1723 /// # Errors
1724 ///
1725 /// This function will return an error in the following situations, but is not
1726 /// limited to just these cases:
1727 ///
1728 /// * `path` does not exist.
1729 /// * A non-final component in path is not a directory.
1730 ///
1731 /// # Examples
1732 ///
1733 /// ```no_run
1734 /// use std::fs;
1735 ///
1736 /// fn main() -> std::io::Result<()> {
1737 ///     let path = fs::canonicalize("../a/../foo.txt")?;
1738 ///     Ok(())
1739 /// }
1740 /// ```
1741 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1742 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1743     fs_imp::canonicalize(path.as_ref())
1744 }
1745
1746 /// Creates a new, empty directory at the provided path
1747 ///
1748 /// # Platform-specific behavior
1749 ///
1750 /// This function currently corresponds to the `mkdir` function on Unix
1751 /// and the `CreateDirectory` function on Windows.
1752 /// Note that, this [may change in the future][changes].
1753 ///
1754 /// [changes]: ../io/index.html#platform-specific-behavior
1755 ///
1756 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1757 /// return an error. To create a directory and all its missing parents at the
1758 /// same time, use the [`create_dir_all`] function.
1759 ///
1760 /// # Errors
1761 ///
1762 /// This function will return an error in the following situations, but is not
1763 /// limited to just these cases:
1764 ///
1765 /// * User lacks permissions to create directory at `path`.
1766 /// * A parent of the given path doesn't exist. (To create a directory and all
1767 ///   its missing parents at the same time, use the [`create_dir_all`]
1768 ///   function.)
1769 /// * `path` already exists.
1770 ///
1771 /// # Examples
1772 ///
1773 /// ```no_run
1774 /// use std::fs;
1775 ///
1776 /// fn main() -> std::io::Result<()> {
1777 ///     fs::create_dir("/some/dir")?;
1778 ///     Ok(())
1779 /// }
1780 /// ```
1781 #[stable(feature = "rust1", since = "1.0.0")]
1782 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1783     DirBuilder::new().create(path.as_ref())
1784 }
1785
1786 /// Recursively create a directory and all of its parent components if they
1787 /// are missing.
1788 ///
1789 /// # Platform-specific behavior
1790 ///
1791 /// This function currently corresponds to the `mkdir` function on Unix
1792 /// and the `CreateDirectory` function on Windows.
1793 /// Note that, this [may change in the future][changes].
1794 ///
1795 /// [changes]: ../io/index.html#platform-specific-behavior
1796 ///
1797 /// # Errors
1798 ///
1799 /// This function will return an error in the following situations, but is not
1800 /// limited to just these cases:
1801 ///
1802 /// * If any directory in the path specified by `path`
1803 /// does not already exist and it could not be created otherwise. The specific
1804 /// error conditions for when a directory is being created (after it is
1805 /// determined to not exist) are outlined by [`fs::create_dir`].
1806 ///
1807 /// Notable exception is made for situations where any of the directories
1808 /// specified in the `path` could not be created as it was being created concurrently.
1809 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1810 /// concurrently from multiple threads or processes is guaranteed not to fail
1811 /// due to a race condition with itself.
1812 ///
1813 /// [`fs::create_dir`]: fn.create_dir.html
1814 ///
1815 /// # Examples
1816 ///
1817 /// ```no_run
1818 /// use std::fs;
1819 ///
1820 /// fn main() -> std::io::Result<()> {
1821 ///     fs::create_dir_all("/some/dir")?;
1822 ///     Ok(())
1823 /// }
1824 /// ```
1825 #[stable(feature = "rust1", since = "1.0.0")]
1826 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1827     DirBuilder::new().recursive(true).create(path.as_ref())
1828 }
1829
1830 /// Removes an existing, empty directory.
1831 ///
1832 /// # Platform-specific behavior
1833 ///
1834 /// This function currently corresponds to the `rmdir` function on Unix
1835 /// and the `RemoveDirectory` function on Windows.
1836 /// Note that, this [may change in the future][changes].
1837 ///
1838 /// [changes]: ../io/index.html#platform-specific-behavior
1839 ///
1840 /// # Errors
1841 ///
1842 /// This function will return an error in the following situations, but is not
1843 /// limited to just these cases:
1844 ///
1845 /// * The user lacks permissions to remove the directory at the provided `path`.
1846 /// * The directory isn't empty.
1847 ///
1848 /// # Examples
1849 ///
1850 /// ```no_run
1851 /// use std::fs;
1852 ///
1853 /// fn main() -> std::io::Result<()> {
1854 ///     fs::remove_dir("/some/dir")?;
1855 ///     Ok(())
1856 /// }
1857 /// ```
1858 #[stable(feature = "rust1", since = "1.0.0")]
1859 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1860     fs_imp::rmdir(path.as_ref())
1861 }
1862
1863 /// Removes a directory at this path, after removing all its contents. Use
1864 /// carefully!
1865 ///
1866 /// This function does **not** follow symbolic links and it will simply remove the
1867 /// symbolic link itself.
1868 ///
1869 /// # Platform-specific behavior
1870 ///
1871 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1872 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1873 /// on Windows.
1874 /// Note that, this [may change in the future][changes].
1875 ///
1876 /// [changes]: ../io/index.html#platform-specific-behavior
1877 ///
1878 /// # Errors
1879 ///
1880 /// See [`fs::remove_file`] and [`fs::remove_dir`].
1881 ///
1882 /// [`fs::remove_file`]:  fn.remove_file.html
1883 /// [`fs::remove_dir`]: fn.remove_dir.html
1884 ///
1885 /// # Examples
1886 ///
1887 /// ```no_run
1888 /// use std::fs;
1889 ///
1890 /// fn main() -> std::io::Result<()> {
1891 ///     fs::remove_dir_all("/some/dir")?;
1892 ///     Ok(())
1893 /// }
1894 /// ```
1895 #[stable(feature = "rust1", since = "1.0.0")]
1896 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1897     fs_imp::remove_dir_all(path.as_ref())
1898 }
1899
1900 /// Returns an iterator over the entries within a directory.
1901 ///
1902 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
1903 /// New errors may be encountered after an iterator is initially constructed.
1904 ///
1905 /// [`io::Result`]: ../io/type.Result.html
1906 /// [`DirEntry`]: struct.DirEntry.html
1907 ///
1908 /// # Platform-specific behavior
1909 ///
1910 /// This function currently corresponds to the `opendir` function on Unix
1911 /// and the `FindFirstFile` function on Windows.
1912 /// Note that, this [may change in the future][changes].
1913 ///
1914 /// [changes]: ../io/index.html#platform-specific-behavior
1915 ///
1916 /// # Errors
1917 ///
1918 /// This function will return an error in the following situations, but is not
1919 /// limited to just these cases:
1920 ///
1921 /// * The provided `path` doesn't exist.
1922 /// * The process lacks permissions to view the contents.
1923 /// * The `path` points at a non-directory file.
1924 ///
1925 /// # Examples
1926 ///
1927 /// ```
1928 /// use std::io;
1929 /// use std::fs::{self, DirEntry};
1930 /// use std::path::Path;
1931 ///
1932 /// // one possible implementation of walking a directory only visiting files
1933 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1934 ///     if dir.is_dir() {
1935 ///         for entry in fs::read_dir(dir)? {
1936 ///             let entry = entry?;
1937 ///             let path = entry.path();
1938 ///             if path.is_dir() {
1939 ///                 visit_dirs(&path, cb)?;
1940 ///             } else {
1941 ///                 cb(&entry);
1942 ///             }
1943 ///         }
1944 ///     }
1945 ///     Ok(())
1946 /// }
1947 /// ```
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1950     fs_imp::readdir(path.as_ref()).map(ReadDir)
1951 }
1952
1953 /// Changes the permissions found on a file or a directory.
1954 ///
1955 /// # Platform-specific behavior
1956 ///
1957 /// This function currently corresponds to the `chmod` function on Unix
1958 /// and the `SetFileAttributes` function on Windows.
1959 /// Note that, this [may change in the future][changes].
1960 ///
1961 /// [changes]: ../io/index.html#platform-specific-behavior
1962 ///
1963 /// # Errors
1964 ///
1965 /// This function will return an error in the following situations, but is not
1966 /// limited to just these cases:
1967 ///
1968 /// * `path` does not exist.
1969 /// * The user lacks the permission to change attributes of the file.
1970 ///
1971 /// # Examples
1972 ///
1973 /// ```no_run
1974 /// use std::fs;
1975 ///
1976 /// fn main() -> std::io::Result<()> {
1977 ///     let mut perms = fs::metadata("foo.txt")?.permissions();
1978 ///     perms.set_readonly(true);
1979 ///     fs::set_permissions("foo.txt", perms)?;
1980 ///     Ok(())
1981 /// }
1982 /// ```
1983 #[stable(feature = "set_permissions", since = "1.1.0")]
1984 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1985                                        -> io::Result<()> {
1986     fs_imp::set_perm(path.as_ref(), perm.0)
1987 }
1988
1989 impl DirBuilder {
1990     /// Creates a new set of options with default mode/security settings for all
1991     /// platforms and also non-recursive.
1992     ///
1993     /// # Examples
1994     ///
1995     /// ```
1996     /// use std::fs::DirBuilder;
1997     ///
1998     /// let builder = DirBuilder::new();
1999     /// ```
2000     #[stable(feature = "dir_builder", since = "1.6.0")]
2001     pub fn new() -> DirBuilder {
2002         DirBuilder {
2003             inner: fs_imp::DirBuilder::new(),
2004             recursive: false,
2005         }
2006     }
2007
2008     /// Indicates that directories should be created recursively, creating all
2009     /// parent directories. Parents that do not exist are created with the same
2010     /// security and permissions settings.
2011     ///
2012     /// This option defaults to `false`.
2013     ///
2014     /// # Examples
2015     ///
2016     /// ```
2017     /// use std::fs::DirBuilder;
2018     ///
2019     /// let mut builder = DirBuilder::new();
2020     /// builder.recursive(true);
2021     /// ```
2022     #[stable(feature = "dir_builder", since = "1.6.0")]
2023     pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2024         self.recursive = recursive;
2025         self
2026     }
2027
2028     /// Creates the specified directory with the options configured in this
2029     /// builder.
2030     ///
2031     /// It is considered an error if the directory already exists unless
2032     /// recursive mode is enabled.
2033     ///
2034     /// # Examples
2035     ///
2036     /// ```no_run
2037     /// use std::fs::{self, DirBuilder};
2038     ///
2039     /// let path = "/tmp/foo/bar/baz";
2040     /// DirBuilder::new()
2041     ///     .recursive(true)
2042     ///     .create(path).unwrap();
2043     ///
2044     /// assert!(fs::metadata(path).unwrap().is_dir());
2045     /// ```
2046     #[stable(feature = "dir_builder", since = "1.6.0")]
2047     pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2048         self._create(path.as_ref())
2049     }
2050
2051     fn _create(&self, path: &Path) -> io::Result<()> {
2052         if self.recursive {
2053             self.create_dir_all(path)
2054         } else {
2055             self.inner.mkdir(path)
2056         }
2057     }
2058
2059     fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2060         if path == Path::new("") {
2061             return Ok(())
2062         }
2063
2064         match self.inner.mkdir(path) {
2065             Ok(()) => return Ok(()),
2066             Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2067             Err(_) if path.is_dir() => return Ok(()),
2068             Err(e) => return Err(e),
2069         }
2070         match path.parent() {
2071             Some(p) => self.create_dir_all(p)?,
2072             None => return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree")),
2073         }
2074         match self.inner.mkdir(path) {
2075             Ok(()) => Ok(()),
2076             Err(_) if path.is_dir() => Ok(()),
2077             Err(e) => Err(e),
2078         }
2079     }
2080 }
2081
2082 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2083     fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2084         &mut self.inner
2085     }
2086 }
2087
2088 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
2089 mod tests {
2090     use io::prelude::*;
2091
2092     use fs::{self, File, OpenOptions};
2093     use io::{ErrorKind, SeekFrom};
2094     use path::Path;
2095     use rand::{rngs::StdRng, FromEntropy, RngCore};
2096     use str;
2097     use sys_common::io::test::{TempDir, tmpdir};
2098     use thread;
2099
2100     #[cfg(windows)]
2101     use os::windows::fs::{symlink_dir, symlink_file};
2102     #[cfg(windows)]
2103     use sys::fs::symlink_junction;
2104     #[cfg(unix)]
2105     use os::unix::fs::symlink as symlink_dir;
2106     #[cfg(unix)]
2107     use os::unix::fs::symlink as symlink_file;
2108     #[cfg(unix)]
2109     use os::unix::fs::symlink as symlink_junction;
2110
2111     macro_rules! check { ($e:expr) => (
2112         match $e {
2113             Ok(t) => t,
2114             Err(e) => panic!("{} failed with: {}", stringify!($e), e),
2115         }
2116     ) }
2117
2118     #[cfg(windows)]
2119     macro_rules! error { ($e:expr, $s:expr) => (
2120         match $e {
2121             Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2122             Err(ref err) => assert!(err.raw_os_error() == Some($s),
2123                                     format!("`{}` did not have a code of `{}`", err, $s))
2124         }
2125     ) }
2126
2127     #[cfg(unix)]
2128     macro_rules! error { ($e:expr, $s:expr) => ( error_contains!($e, $s) ) }
2129
2130     macro_rules! error_contains { ($e:expr, $s:expr) => (
2131         match $e {
2132             Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2133             Err(ref err) => assert!(err.to_string().contains($s),
2134                                     format!("`{}` did not contain `{}`", err, $s))
2135         }
2136     ) }
2137
2138     // Several test fail on windows if the user does not have permission to
2139     // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
2140     // disabling these test on Windows, use this function to test whether we
2141     // have permission, and return otherwise. This way, we still don't run these
2142     // tests most of the time, but at least we do if the user has the right
2143     // permissions.
2144     pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
2145         if cfg!(unix) { return true }
2146         let link = tmpdir.join("some_hopefully_unique_link_name");
2147
2148         match symlink_file(r"nonexisting_target", link) {
2149             Ok(_) => true,
2150             // ERROR_PRIVILEGE_NOT_HELD = 1314
2151             Err(ref err) if err.raw_os_error() == Some(1314) => false,
2152             Err(_) => true,
2153         }
2154     }
2155
2156     #[test]
2157     fn file_test_io_smoke_test() {
2158         let message = "it's alright. have a good time";
2159         let tmpdir = tmpdir();
2160         let filename = &tmpdir.join("file_rt_io_file_test.txt");
2161         {
2162             let mut write_stream = check!(File::create(filename));
2163             check!(write_stream.write(message.as_bytes()));
2164         }
2165         {
2166             let mut read_stream = check!(File::open(filename));
2167             let mut read_buf = [0; 1028];
2168             let read_str = match check!(read_stream.read(&mut read_buf)) {
2169                 0 => panic!("shouldn't happen"),
2170                 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
2171             };
2172             assert_eq!(read_str, message);
2173         }
2174         check!(fs::remove_file(filename));
2175     }
2176
2177     #[test]
2178     fn invalid_path_raises() {
2179         let tmpdir = tmpdir();
2180         let filename = &tmpdir.join("file_that_does_not_exist.txt");
2181         let result = File::open(filename);
2182
2183         #[cfg(unix)]
2184         error!(result, "No such file or directory");
2185         #[cfg(windows)]
2186         error!(result, 2); // ERROR_FILE_NOT_FOUND
2187     }
2188
2189     #[test]
2190     fn file_test_iounlinking_invalid_path_should_raise_condition() {
2191         let tmpdir = tmpdir();
2192         let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
2193
2194         let result = fs::remove_file(filename);
2195
2196         #[cfg(unix)]
2197         error!(result, "No such file or directory");
2198         #[cfg(windows)]
2199         error!(result, 2); // ERROR_FILE_NOT_FOUND
2200     }
2201
2202     #[test]
2203     fn file_test_io_non_positional_read() {
2204         let message: &str = "ten-four";
2205         let mut read_mem = [0; 8];
2206         let tmpdir = tmpdir();
2207         let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
2208         {
2209             let mut rw_stream = check!(File::create(filename));
2210             check!(rw_stream.write(message.as_bytes()));
2211         }
2212         {
2213             let mut read_stream = check!(File::open(filename));
2214             {
2215                 let read_buf = &mut read_mem[0..4];
2216                 check!(read_stream.read(read_buf));
2217             }
2218             {
2219                 let read_buf = &mut read_mem[4..8];
2220                 check!(read_stream.read(read_buf));
2221             }
2222         }
2223         check!(fs::remove_file(filename));
2224         let read_str = str::from_utf8(&read_mem).unwrap();
2225         assert_eq!(read_str, message);
2226     }
2227
2228     #[test]
2229     fn file_test_io_seek_and_tell_smoke_test() {
2230         let message = "ten-four";
2231         let mut read_mem = [0; 4];
2232         let set_cursor = 4 as u64;
2233         let tell_pos_pre_read;
2234         let tell_pos_post_read;
2235         let tmpdir = tmpdir();
2236         let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
2237         {
2238             let mut rw_stream = check!(File::create(filename));
2239             check!(rw_stream.write(message.as_bytes()));
2240         }
2241         {
2242             let mut read_stream = check!(File::open(filename));
2243             check!(read_stream.seek(SeekFrom::Start(set_cursor)));
2244             tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
2245             check!(read_stream.read(&mut read_mem));
2246             tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
2247         }
2248         check!(fs::remove_file(filename));
2249         let read_str = str::from_utf8(&read_mem).unwrap();
2250         assert_eq!(read_str, &message[4..8]);
2251         assert_eq!(tell_pos_pre_read, set_cursor);
2252         assert_eq!(tell_pos_post_read, message.len() as u64);
2253     }
2254
2255     #[test]
2256     fn file_test_io_seek_and_write() {
2257         let initial_msg =   "food-is-yummy";
2258         let overwrite_msg =    "-the-bar!!";
2259         let final_msg =     "foo-the-bar!!";
2260         let seek_idx = 3;
2261         let mut read_mem = [0; 13];
2262         let tmpdir = tmpdir();
2263         let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
2264         {
2265             let mut rw_stream = check!(File::create(filename));
2266             check!(rw_stream.write(initial_msg.as_bytes()));
2267             check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
2268             check!(rw_stream.write(overwrite_msg.as_bytes()));
2269         }
2270         {
2271             let mut read_stream = check!(File::open(filename));
2272             check!(read_stream.read(&mut read_mem));
2273         }
2274         check!(fs::remove_file(filename));
2275         let read_str = str::from_utf8(&read_mem).unwrap();
2276         assert!(read_str == final_msg);
2277     }
2278
2279     #[test]
2280     fn file_test_io_seek_shakedown() {
2281         //                   01234567890123
2282         let initial_msg =   "qwer-asdf-zxcv";
2283         let chunk_one: &str = "qwer";
2284         let chunk_two: &str = "asdf";
2285         let chunk_three: &str = "zxcv";
2286         let mut read_mem = [0; 4];
2287         let tmpdir = tmpdir();
2288         let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2289         {
2290             let mut rw_stream = check!(File::create(filename));
2291             check!(rw_stream.write(initial_msg.as_bytes()));
2292         }
2293         {
2294             let mut read_stream = check!(File::open(filename));
2295
2296             check!(read_stream.seek(SeekFrom::End(-4)));
2297             check!(read_stream.read(&mut read_mem));
2298             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2299
2300             check!(read_stream.seek(SeekFrom::Current(-9)));
2301             check!(read_stream.read(&mut read_mem));
2302             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2303
2304             check!(read_stream.seek(SeekFrom::Start(0)));
2305             check!(read_stream.read(&mut read_mem));
2306             assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2307         }
2308         check!(fs::remove_file(filename));
2309     }
2310
2311     #[test]
2312     fn file_test_io_eof() {
2313         let tmpdir = tmpdir();
2314         let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2315         let mut buf = [0; 256];
2316         {
2317             let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2318             let mut rw = check!(oo.open(&filename));
2319             assert_eq!(check!(rw.read(&mut buf)), 0);
2320             assert_eq!(check!(rw.read(&mut buf)), 0);
2321         }
2322         check!(fs::remove_file(&filename));
2323     }
2324
2325     #[test]
2326     #[cfg(unix)]
2327     fn file_test_io_read_write_at() {
2328         use os::unix::fs::FileExt;
2329
2330         let tmpdir = tmpdir();
2331         let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2332         let mut buf = [0; 256];
2333         let write1 = "asdf";
2334         let write2 = "qwer-";
2335         let write3 = "-zxcv";
2336         let content = "qwer-asdf-zxcv";
2337         {
2338             let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2339             let mut rw = check!(oo.open(&filename));
2340             assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2341             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2342             assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2343             assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2344             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2345             assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2346             assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2347             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2348             assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2349             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2350             assert_eq!(check!(rw.read(&mut buf)), write1.len());
2351             assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2352             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2353             assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2354             assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2355             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2356             assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2357             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2358         }
2359         {
2360             let mut read = check!(File::open(&filename));
2361             assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2362             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2363             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2364             assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2365             assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2366             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2367             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2368             assert_eq!(check!(read.read(&mut buf)), write3.len());
2369             assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2370             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2371             assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2372             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2373             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2374             assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2375             assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2376             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2377         }
2378         check!(fs::remove_file(&filename));
2379     }
2380
2381     #[test]
2382     #[cfg(unix)]
2383     fn set_get_unix_permissions() {
2384         use os::unix::fs::PermissionsExt;
2385
2386         let tmpdir = tmpdir();
2387         let filename = &tmpdir.join("set_get_unix_permissions");
2388         check!(fs::create_dir(filename));
2389         let mask = 0o7777;
2390
2391         check!(fs::set_permissions(filename,
2392                                    fs::Permissions::from_mode(0)));
2393         let metadata0 = check!(fs::metadata(filename));
2394         assert_eq!(mask & metadata0.permissions().mode(), 0);
2395
2396         check!(fs::set_permissions(filename,
2397                                    fs::Permissions::from_mode(0o1777)));
2398         let metadata1 = check!(fs::metadata(filename));
2399         assert_eq!(mask & metadata1.permissions().mode(), 0o1777);
2400     }
2401
2402     #[test]
2403     #[cfg(windows)]
2404     fn file_test_io_seek_read_write() {
2405         use os::windows::fs::FileExt;
2406
2407         let tmpdir = tmpdir();
2408         let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2409         let mut buf = [0; 256];
2410         let write1 = "asdf";
2411         let write2 = "qwer-";
2412         let write3 = "-zxcv";
2413         let content = "qwer-asdf-zxcv";
2414         {
2415             let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2416             let mut rw = check!(oo.open(&filename));
2417             assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2418             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2419             assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2420             assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2421             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2422             assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2423             assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2424             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2425             assert_eq!(check!(rw.read(&mut buf)), write1.len());
2426             assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2427             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2428             assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2429             assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2430             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2431             assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2432             assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2433         }
2434         {
2435             let mut read = check!(File::open(&filename));
2436             assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2437             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2438             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2439             assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2440             assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2441             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2442             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2443             assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2444             assert_eq!(check!(read.read(&mut buf)), write3.len());
2445             assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2446             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2447             assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2448             assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2449             assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2450             assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2451             assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2452         }
2453         check!(fs::remove_file(&filename));
2454     }
2455
2456     #[test]
2457     fn file_test_stat_is_correct_on_is_file() {
2458         let tmpdir = tmpdir();
2459         let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2460         {
2461             let mut opts = OpenOptions::new();
2462             let mut fs = check!(opts.read(true).write(true)
2463                                     .create(true).open(filename));
2464             let msg = "hw";
2465             fs.write(msg.as_bytes()).unwrap();
2466
2467             let fstat_res = check!(fs.metadata());
2468             assert!(fstat_res.is_file());
2469         }
2470         let stat_res_fn = check!(fs::metadata(filename));
2471         assert!(stat_res_fn.is_file());
2472         let stat_res_meth = check!(filename.metadata());
2473         assert!(stat_res_meth.is_file());
2474         check!(fs::remove_file(filename));
2475     }
2476
2477     #[test]
2478     fn file_test_stat_is_correct_on_is_dir() {
2479         let tmpdir = tmpdir();
2480         let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2481         check!(fs::create_dir(filename));
2482         let stat_res_fn = check!(fs::metadata(filename));
2483         assert!(stat_res_fn.is_dir());
2484         let stat_res_meth = check!(filename.metadata());
2485         assert!(stat_res_meth.is_dir());
2486         check!(fs::remove_dir(filename));
2487     }
2488
2489     #[test]
2490     fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2491         let tmpdir = tmpdir();
2492         let dir = &tmpdir.join("fileinfo_false_on_dir");
2493         check!(fs::create_dir(dir));
2494         assert!(!dir.is_file());
2495         check!(fs::remove_dir(dir));
2496     }
2497
2498     #[test]
2499     fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2500         let tmpdir = tmpdir();
2501         let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2502         check!(check!(File::create(file)).write(b"foo"));
2503         assert!(file.exists());
2504         check!(fs::remove_file(file));
2505         assert!(!file.exists());
2506     }
2507
2508     #[test]
2509     fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2510         let tmpdir = tmpdir();
2511         let dir = &tmpdir.join("before_and_after_dir");
2512         assert!(!dir.exists());
2513         check!(fs::create_dir(dir));
2514         assert!(dir.exists());
2515         assert!(dir.is_dir());
2516         check!(fs::remove_dir(dir));
2517         assert!(!dir.exists());
2518     }
2519
2520     #[test]
2521     fn file_test_directoryinfo_readdir() {
2522         let tmpdir = tmpdir();
2523         let dir = &tmpdir.join("di_readdir");
2524         check!(fs::create_dir(dir));
2525         let prefix = "foo";
2526         for n in 0..3 {
2527             let f = dir.join(&format!("{}.txt", n));
2528             let mut w = check!(File::create(&f));
2529             let msg_str = format!("{}{}", prefix, n.to_string());
2530             let msg = msg_str.as_bytes();
2531             check!(w.write(msg));
2532         }
2533         let files = check!(fs::read_dir(dir));
2534         let mut mem = [0; 4];
2535         for f in files {
2536             let f = f.unwrap().path();
2537             {
2538                 let n = f.file_stem().unwrap();
2539                 check!(check!(File::open(&f)).read(&mut mem));
2540                 let read_str = str::from_utf8(&mem).unwrap();
2541                 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2542                 assert_eq!(expected, read_str);
2543             }
2544             check!(fs::remove_file(&f));
2545         }
2546         check!(fs::remove_dir(dir));
2547     }
2548
2549     #[test]
2550     fn file_create_new_already_exists_error() {
2551         let tmpdir = tmpdir();
2552         let file = &tmpdir.join("file_create_new_error_exists");
2553         check!(fs::File::create(file));
2554         let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2555         assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2556     }
2557
2558     #[test]
2559     fn mkdir_path_already_exists_error() {
2560         let tmpdir = tmpdir();
2561         let dir = &tmpdir.join("mkdir_error_twice");
2562         check!(fs::create_dir(dir));
2563         let e = fs::create_dir(dir).unwrap_err();
2564         assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2565     }
2566
2567     #[test]
2568     fn recursive_mkdir() {
2569         let tmpdir = tmpdir();
2570         let dir = tmpdir.join("d1/d2");
2571         check!(fs::create_dir_all(&dir));
2572         assert!(dir.is_dir())
2573     }
2574
2575     #[test]
2576     fn recursive_mkdir_failure() {
2577         let tmpdir = tmpdir();
2578         let dir = tmpdir.join("d1");
2579         let file = dir.join("f1");
2580
2581         check!(fs::create_dir_all(&dir));
2582         check!(File::create(&file));
2583
2584         let result = fs::create_dir_all(&file);
2585
2586         assert!(result.is_err());
2587     }
2588
2589     #[test]
2590     fn concurrent_recursive_mkdir() {
2591         for _ in 0..100 {
2592             let dir = tmpdir();
2593             let mut dir = dir.join("a");
2594             for _ in 0..40 {
2595                 dir = dir.join("a");
2596             }
2597             let mut join = vec!();
2598             for _ in 0..8 {
2599                 let dir = dir.clone();
2600                 join.push(thread::spawn(move || {
2601                     check!(fs::create_dir_all(&dir));
2602                 }))
2603             }
2604
2605             // No `Display` on result of `join()`
2606             join.drain(..).map(|join| join.join().unwrap()).count();
2607         }
2608     }
2609
2610     #[test]
2611     fn recursive_mkdir_slash() {
2612         check!(fs::create_dir_all(Path::new("/")));
2613     }
2614
2615     #[test]
2616     fn recursive_mkdir_dot() {
2617         check!(fs::create_dir_all(Path::new(".")));
2618     }
2619
2620     #[test]
2621     fn recursive_mkdir_empty() {
2622         check!(fs::create_dir_all(Path::new("")));
2623     }
2624
2625     #[test]
2626     fn recursive_rmdir() {
2627         let tmpdir = tmpdir();
2628         let d1 = tmpdir.join("d1");
2629         let dt = d1.join("t");
2630         let dtt = dt.join("t");
2631         let d2 = tmpdir.join("d2");
2632         let canary = d2.join("do_not_delete");
2633         check!(fs::create_dir_all(&dtt));
2634         check!(fs::create_dir_all(&d2));
2635         check!(check!(File::create(&canary)).write(b"foo"));
2636         check!(symlink_junction(&d2, &dt.join("d2")));
2637         let _ = symlink_file(&canary, &d1.join("canary"));
2638         check!(fs::remove_dir_all(&d1));
2639
2640         assert!(!d1.is_dir());
2641         assert!(canary.exists());
2642     }
2643
2644     #[test]
2645     fn recursive_rmdir_of_symlink() {
2646         // test we do not recursively delete a symlink but only dirs.
2647         let tmpdir = tmpdir();
2648         let link = tmpdir.join("d1");
2649         let dir = tmpdir.join("d2");
2650         let canary = dir.join("do_not_delete");
2651         check!(fs::create_dir_all(&dir));
2652         check!(check!(File::create(&canary)).write(b"foo"));
2653         check!(symlink_junction(&dir, &link));
2654         check!(fs::remove_dir_all(&link));
2655
2656         assert!(!link.is_dir());
2657         assert!(canary.exists());
2658     }
2659
2660     #[test]
2661     // only Windows makes a distinction between file and directory symlinks.
2662     #[cfg(windows)]
2663     fn recursive_rmdir_of_file_symlink() {
2664         let tmpdir = tmpdir();
2665         if !got_symlink_permission(&tmpdir) { return };
2666
2667         let f1 = tmpdir.join("f1");
2668         let f2 = tmpdir.join("f2");
2669         check!(check!(File::create(&f1)).write(b"foo"));
2670         check!(symlink_file(&f1, &f2));
2671         match fs::remove_dir_all(&f2) {
2672             Ok(..) => panic!("wanted a failure"),
2673             Err(..) => {}
2674         }
2675     }
2676
2677     #[test]
2678     fn unicode_path_is_dir() {
2679         assert!(Path::new(".").is_dir());
2680         assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2681
2682         let tmpdir = tmpdir();
2683
2684         let mut dirpath = tmpdir.path().to_path_buf();
2685         dirpath.push("test-가一ー你好");
2686         check!(fs::create_dir(&dirpath));
2687         assert!(dirpath.is_dir());
2688
2689         let mut filepath = dirpath;
2690         filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2691         check!(File::create(&filepath)); // ignore return; touch only
2692         assert!(!filepath.is_dir());
2693         assert!(filepath.exists());
2694     }
2695
2696     #[test]
2697     fn unicode_path_exists() {
2698         assert!(Path::new(".").exists());
2699         assert!(!Path::new("test/nonexistent-bogus-path").exists());
2700
2701         let tmpdir = tmpdir();
2702         let unicode = tmpdir.path();
2703         let unicode = unicode.join("test-각丁ー再见");
2704         check!(fs::create_dir(&unicode));
2705         assert!(unicode.exists());
2706         assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2707     }
2708
2709     #[test]
2710     fn copy_file_does_not_exist() {
2711         let from = Path::new("test/nonexistent-bogus-path");
2712         let to = Path::new("test/other-bogus-path");
2713
2714         match fs::copy(&from, &to) {
2715             Ok(..) => panic!(),
2716             Err(..) => {
2717                 assert!(!from.exists());
2718                 assert!(!to.exists());
2719             }
2720         }
2721     }
2722
2723     #[test]
2724     fn copy_src_does_not_exist() {
2725         let tmpdir = tmpdir();
2726         let from = Path::new("test/nonexistent-bogus-path");
2727         let to = tmpdir.join("out.txt");
2728         check!(check!(File::create(&to)).write(b"hello"));
2729         assert!(fs::copy(&from, &to).is_err());
2730         assert!(!from.exists());
2731         let mut v = Vec::new();
2732         check!(check!(File::open(&to)).read_to_end(&mut v));
2733         assert_eq!(v, b"hello");
2734     }
2735
2736     #[test]
2737     fn copy_file_ok() {
2738         let tmpdir = tmpdir();
2739         let input = tmpdir.join("in.txt");
2740         let out = tmpdir.join("out.txt");
2741
2742         check!(check!(File::create(&input)).write(b"hello"));
2743         check!(fs::copy(&input, &out));
2744         let mut v = Vec::new();
2745         check!(check!(File::open(&out)).read_to_end(&mut v));
2746         assert_eq!(v, b"hello");
2747
2748         assert_eq!(check!(input.metadata()).permissions(),
2749                    check!(out.metadata()).permissions());
2750     }
2751
2752     #[test]
2753     fn copy_file_dst_dir() {
2754         let tmpdir = tmpdir();
2755         let out = tmpdir.join("out");
2756
2757         check!(File::create(&out));
2758         match fs::copy(&*out, tmpdir.path()) {
2759             Ok(..) => panic!(), Err(..) => {}
2760         }
2761     }
2762
2763     #[test]
2764     fn copy_file_dst_exists() {
2765         let tmpdir = tmpdir();
2766         let input = tmpdir.join("in");
2767         let output = tmpdir.join("out");
2768
2769         check!(check!(File::create(&input)).write("foo".as_bytes()));
2770         check!(check!(File::create(&output)).write("bar".as_bytes()));
2771         check!(fs::copy(&input, &output));
2772
2773         let mut v = Vec::new();
2774         check!(check!(File::open(&output)).read_to_end(&mut v));
2775         assert_eq!(v, b"foo".to_vec());
2776     }
2777
2778     #[test]
2779     fn copy_file_src_dir() {
2780         let tmpdir = tmpdir();
2781         let out = tmpdir.join("out");
2782
2783         match fs::copy(tmpdir.path(), &out) {
2784             Ok(..) => panic!(), Err(..) => {}
2785         }
2786         assert!(!out.exists());
2787     }
2788
2789     #[test]
2790     fn copy_file_preserves_perm_bits() {
2791         let tmpdir = tmpdir();
2792         let input = tmpdir.join("in.txt");
2793         let out = tmpdir.join("out.txt");
2794
2795         let attr = check!(check!(File::create(&input)).metadata());
2796         let mut p = attr.permissions();
2797         p.set_readonly(true);
2798         check!(fs::set_permissions(&input, p));
2799         check!(fs::copy(&input, &out));
2800         assert!(check!(out.metadata()).permissions().readonly());
2801         check!(fs::set_permissions(&input, attr.permissions()));
2802         check!(fs::set_permissions(&out, attr.permissions()));
2803     }
2804
2805     #[test]
2806     #[cfg(windows)]
2807     fn copy_file_preserves_streams() {
2808         let tmp = tmpdir();
2809         check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2810         assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 0);
2811         assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2812         let mut v = Vec::new();
2813         check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2814         assert_eq!(v, b"carrot".to_vec());
2815     }
2816
2817     #[test]
2818     fn copy_file_returns_metadata_len() {
2819         let tmp = tmpdir();
2820         let in_path = tmp.join("in.txt");
2821         let out_path = tmp.join("out.txt");
2822         check!(check!(File::create(&in_path)).write(b"lettuce"));
2823         #[cfg(windows)]
2824         check!(check!(File::create(tmp.join("in.txt:bunny"))).write(b"carrot"));
2825         let copied_len = check!(fs::copy(&in_path, &out_path));
2826         assert_eq!(check!(out_path.metadata()).len(), copied_len);
2827     }
2828
2829     #[test]
2830     fn symlinks_work() {
2831         let tmpdir = tmpdir();
2832         if !got_symlink_permission(&tmpdir) { return };
2833
2834         let input = tmpdir.join("in.txt");
2835         let out = tmpdir.join("out.txt");
2836
2837         check!(check!(File::create(&input)).write("foobar".as_bytes()));
2838         check!(symlink_file(&input, &out));
2839         assert!(check!(out.symlink_metadata()).file_type().is_symlink());
2840         assert_eq!(check!(fs::metadata(&out)).len(),
2841                    check!(fs::metadata(&input)).len());
2842         let mut v = Vec::new();
2843         check!(check!(File::open(&out)).read_to_end(&mut v));
2844         assert_eq!(v, b"foobar".to_vec());
2845     }
2846
2847     #[test]
2848     fn symlink_noexist() {
2849         // Symlinks can point to things that don't exist
2850         let tmpdir = tmpdir();
2851         if !got_symlink_permission(&tmpdir) { return };
2852
2853         // Use a relative path for testing. Symlinks get normalized by Windows,
2854         // so we may not get the same path back for absolute paths
2855         check!(symlink_file(&"foo", &tmpdir.join("bar")));
2856         assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(),
2857                    "foo");
2858     }
2859
2860     #[test]
2861     fn read_link() {
2862         if cfg!(windows) {
2863             // directory symlink
2864             assert_eq!(check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
2865                        r"C:\ProgramData");
2866             // junction
2867             assert_eq!(check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
2868                        r"C:\Users\Default");
2869             // junction with special permissions
2870             assert_eq!(check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
2871                        r"C:\Users");
2872         }
2873         let tmpdir = tmpdir();
2874         let link = tmpdir.join("link");
2875         if !got_symlink_permission(&tmpdir) { return };
2876         check!(symlink_file(&"foo", &link));
2877         assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
2878     }
2879
2880     #[test]
2881     fn readlink_not_symlink() {
2882         let tmpdir = tmpdir();
2883         match fs::read_link(tmpdir.path()) {
2884             Ok(..) => panic!("wanted a failure"),
2885             Err(..) => {}
2886         }
2887     }
2888
2889     #[test]
2890     fn links_work() {
2891         let tmpdir = tmpdir();
2892         let input = tmpdir.join("in.txt");
2893         let out = tmpdir.join("out.txt");
2894
2895         check!(check!(File::create(&input)).write("foobar".as_bytes()));
2896         check!(fs::hard_link(&input, &out));
2897         assert_eq!(check!(fs::metadata(&out)).len(),
2898                    check!(fs::metadata(&input)).len());
2899         assert_eq!(check!(fs::metadata(&out)).len(),
2900                    check!(input.metadata()).len());
2901         let mut v = Vec::new();
2902         check!(check!(File::open(&out)).read_to_end(&mut v));
2903         assert_eq!(v, b"foobar".to_vec());
2904
2905         // can't link to yourself
2906         match fs::hard_link(&input, &input) {
2907             Ok(..) => panic!("wanted a failure"),
2908             Err(..) => {}
2909         }
2910         // can't link to something that doesn't exist
2911         match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
2912             Ok(..) => panic!("wanted a failure"),
2913             Err(..) => {}
2914         }
2915     }
2916
2917     #[test]
2918     fn chmod_works() {
2919         let tmpdir = tmpdir();
2920         let file = tmpdir.join("in.txt");
2921
2922         check!(File::create(&file));
2923         let attr = check!(fs::metadata(&file));
2924         assert!(!attr.permissions().readonly());
2925         let mut p = attr.permissions();
2926         p.set_readonly(true);
2927         check!(fs::set_permissions(&file, p.clone()));
2928         let attr = check!(fs::metadata(&file));
2929         assert!(attr.permissions().readonly());
2930
2931         match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
2932             Ok(..) => panic!("wanted an error"),
2933             Err(..) => {}
2934         }
2935
2936         p.set_readonly(false);
2937         check!(fs::set_permissions(&file, p));
2938     }
2939
2940     #[test]
2941     fn fchmod_works() {
2942         let tmpdir = tmpdir();
2943         let path = tmpdir.join("in.txt");
2944
2945         let file = check!(File::create(&path));
2946         let attr = check!(fs::metadata(&path));
2947         assert!(!attr.permissions().readonly());
2948         let mut p = attr.permissions();
2949         p.set_readonly(true);
2950         check!(file.set_permissions(p.clone()));
2951         let attr = check!(fs::metadata(&path));
2952         assert!(attr.permissions().readonly());
2953
2954         p.set_readonly(false);
2955         check!(file.set_permissions(p));
2956     }
2957
2958     #[test]
2959     fn sync_doesnt_kill_anything() {
2960         let tmpdir = tmpdir();
2961         let path = tmpdir.join("in.txt");
2962
2963         let mut file = check!(File::create(&path));
2964         check!(file.sync_all());
2965         check!(file.sync_data());
2966         check!(file.write(b"foo"));
2967         check!(file.sync_all());
2968         check!(file.sync_data());
2969     }
2970
2971     #[test]
2972     fn truncate_works() {
2973         let tmpdir = tmpdir();
2974         let path = tmpdir.join("in.txt");
2975
2976         let mut file = check!(File::create(&path));
2977         check!(file.write(b"foo"));
2978         check!(file.sync_all());
2979
2980         // Do some simple things with truncation
2981         assert_eq!(check!(file.metadata()).len(), 3);
2982         check!(file.set_len(10));
2983         assert_eq!(check!(file.metadata()).len(), 10);
2984         check!(file.write(b"bar"));
2985         check!(file.sync_all());
2986         assert_eq!(check!(file.metadata()).len(), 10);
2987
2988         let mut v = Vec::new();
2989         check!(check!(File::open(&path)).read_to_end(&mut v));
2990         assert_eq!(v, b"foobar\0\0\0\0".to_vec());
2991
2992         // Truncate to a smaller length, don't seek, and then write something.
2993         // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
2994         // past the end of the file).
2995         check!(file.set_len(2));
2996         assert_eq!(check!(file.metadata()).len(), 2);
2997         check!(file.write(b"wut"));
2998         check!(file.sync_all());
2999         assert_eq!(check!(file.metadata()).len(), 9);
3000         let mut v = Vec::new();
3001         check!(check!(File::open(&path)).read_to_end(&mut v));
3002         assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
3003     }
3004
3005     #[test]
3006     fn open_flavors() {
3007         use fs::OpenOptions as OO;
3008         fn c<T: Clone>(t: &T) -> T { t.clone() }
3009
3010         let tmpdir = tmpdir();
3011
3012         let mut r = OO::new(); r.read(true);
3013         let mut w = OO::new(); w.write(true);
3014         let mut rw = OO::new(); rw.read(true).write(true);
3015         let mut a = OO::new(); a.append(true);
3016         let mut ra = OO::new(); ra.read(true).append(true);
3017
3018         #[cfg(windows)]
3019         let invalid_options = 87; // ERROR_INVALID_PARAMETER
3020         #[cfg(unix)]
3021         let invalid_options = "Invalid argument";
3022
3023         // Test various combinations of creation modes and access modes.
3024         //
3025         // Allowed:
3026         // creation mode           | read  | write | read-write | append | read-append |
3027         // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
3028         // not set (open existing) |   X   |   X   |     X      |   X    |      X      |
3029         // create                  |       |   X   |     X      |   X    |      X      |
3030         // truncate                |       |   X   |     X      |        |             |
3031         // create and truncate     |       |   X   |     X      |        |             |
3032         // create_new              |       |   X   |     X      |   X    |      X      |
3033         //
3034         // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
3035
3036         // write-only
3037         check!(c(&w).create_new(true).open(&tmpdir.join("a")));
3038         check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
3039         check!(c(&w).truncate(true).open(&tmpdir.join("a")));
3040         check!(c(&w).create(true).open(&tmpdir.join("a")));
3041         check!(c(&w).open(&tmpdir.join("a")));
3042
3043         // read-only
3044         error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
3045         error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
3046         error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
3047         error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
3048         check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
3049
3050         // read-write
3051         check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
3052         check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
3053         check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
3054         check!(c(&rw).create(true).open(&tmpdir.join("c")));
3055         check!(c(&rw).open(&tmpdir.join("c")));
3056
3057         // append
3058         check!(c(&a).create_new(true).open(&tmpdir.join("d")));
3059         error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
3060         error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
3061         check!(c(&a).create(true).open(&tmpdir.join("d")));
3062         check!(c(&a).open(&tmpdir.join("d")));
3063
3064         // read-append
3065         check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
3066         error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
3067         error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
3068         check!(c(&ra).create(true).open(&tmpdir.join("e")));
3069         check!(c(&ra).open(&tmpdir.join("e")));
3070
3071         // Test opening a file without setting an access mode
3072         let mut blank = OO::new();
3073          error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
3074
3075         // Test write works
3076         check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
3077
3078         // Test write fails for read-only
3079         check!(r.open(&tmpdir.join("h")));
3080         {
3081             let mut f = check!(r.open(&tmpdir.join("h")));
3082             assert!(f.write("wut".as_bytes()).is_err());
3083         }
3084
3085         // Test write overwrites
3086         {
3087             let mut f = check!(c(&w).open(&tmpdir.join("h")));
3088             check!(f.write("baz".as_bytes()));
3089         }
3090         {
3091             let mut f = check!(c(&r).open(&tmpdir.join("h")));
3092             let mut b = vec![0; 6];
3093             check!(f.read(&mut b));
3094             assert_eq!(b, "bazbar".as_bytes());
3095         }
3096
3097         // Test truncate works
3098         {
3099             let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
3100             check!(f.write("foo".as_bytes()));
3101         }
3102         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3103
3104         // Test append works
3105         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3106         {
3107             let mut f = check!(c(&a).open(&tmpdir.join("h")));
3108             check!(f.write("bar".as_bytes()));
3109         }
3110         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
3111
3112         // Test .append(true) equals .write(true).append(true)
3113         {
3114             let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
3115             check!(f.write("baz".as_bytes()));
3116         }
3117         assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
3118     }
3119
3120     #[test]
3121     fn _assert_send_sync() {
3122         fn _assert_send_sync<T: Send + Sync>() {}
3123         _assert_send_sync::<OpenOptions>();
3124     }
3125
3126     #[test]
3127     fn binary_file() {
3128         let mut bytes = [0; 1024];
3129         StdRng::from_entropy().fill_bytes(&mut bytes);
3130
3131         let tmpdir = tmpdir();
3132
3133         check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
3134         let mut v = Vec::new();
3135         check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
3136         assert!(v == &bytes[..]);
3137     }
3138
3139     #[test]
3140     fn write_then_read() {
3141         let mut bytes = [0; 1024];
3142         StdRng::from_entropy().fill_bytes(&mut bytes);
3143
3144         let tmpdir = tmpdir();
3145
3146         check!(fs::write(&tmpdir.join("test"), &bytes[..]));
3147         let v = check!(fs::read(&tmpdir.join("test")));
3148         assert!(v == &bytes[..]);
3149
3150         check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF]));
3151         error_contains!(fs::read_to_string(&tmpdir.join("not-utf8")),
3152                         "stream did not contain valid UTF-8");
3153
3154         let s = "𐁁𐀓𐀠𐀴𐀍";
3155         check!(fs::write(&tmpdir.join("utf8"), s.as_bytes()));
3156         let string = check!(fs::read_to_string(&tmpdir.join("utf8")));
3157         assert_eq!(string, s);
3158     }
3159
3160     #[test]
3161     fn file_try_clone() {
3162         let tmpdir = tmpdir();
3163
3164         let mut f1 = check!(OpenOptions::new()
3165                                        .read(true)
3166                                        .write(true)
3167                                        .create(true)
3168                                        .open(&tmpdir.join("test")));
3169         let mut f2 = check!(f1.try_clone());
3170
3171         check!(f1.write_all(b"hello world"));
3172         check!(f1.seek(SeekFrom::Start(2)));
3173
3174         let mut buf = vec![];
3175         check!(f2.read_to_end(&mut buf));
3176         assert_eq!(buf, b"llo world");
3177         drop(f2);
3178
3179         check!(f1.write_all(b"!"));
3180     }
3181
3182     #[test]
3183     #[cfg(not(windows))]
3184     fn unlink_readonly() {
3185         let tmpdir = tmpdir();
3186         let path = tmpdir.join("file");
3187         check!(File::create(&path));
3188         let mut perm = check!(fs::metadata(&path)).permissions();
3189         perm.set_readonly(true);
3190         check!(fs::set_permissions(&path, perm));
3191         check!(fs::remove_file(&path));
3192     }
3193
3194     #[test]
3195     fn mkdir_trailing_slash() {
3196         let tmpdir = tmpdir();
3197         let path = tmpdir.join("file");
3198         check!(fs::create_dir_all(&path.join("a/")));
3199     }
3200
3201     #[test]
3202     fn canonicalize_works_simple() {
3203         let tmpdir = tmpdir();
3204         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3205         let file = tmpdir.join("test");
3206         File::create(&file).unwrap();
3207         assert_eq!(fs::canonicalize(&file).unwrap(), file);
3208     }
3209
3210     #[test]
3211     fn realpath_works() {
3212         let tmpdir = tmpdir();
3213         if !got_symlink_permission(&tmpdir) { return };
3214
3215         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3216         let file = tmpdir.join("test");
3217         let dir = tmpdir.join("test2");
3218         let link = dir.join("link");
3219         let linkdir = tmpdir.join("test3");
3220
3221         File::create(&file).unwrap();
3222         fs::create_dir(&dir).unwrap();
3223         symlink_file(&file, &link).unwrap();
3224         symlink_dir(&dir, &linkdir).unwrap();
3225
3226         assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
3227
3228         assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
3229         assert_eq!(fs::canonicalize(&file).unwrap(), file);
3230         assert_eq!(fs::canonicalize(&link).unwrap(), file);
3231         assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
3232         assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
3233     }
3234
3235     #[test]
3236     fn realpath_works_tricky() {
3237         let tmpdir = tmpdir();
3238         if !got_symlink_permission(&tmpdir) { return };
3239
3240         let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3241         let a = tmpdir.join("a");
3242         let b = a.join("b");
3243         let c = b.join("c");
3244         let d = a.join("d");
3245         let e = d.join("e");
3246         let f = a.join("f");
3247
3248         fs::create_dir_all(&b).unwrap();
3249         fs::create_dir_all(&d).unwrap();
3250         File::create(&f).unwrap();
3251         if cfg!(not(windows)) {
3252             symlink_dir("../d/e", &c).unwrap();
3253             symlink_file("../f", &e).unwrap();
3254         }
3255         if cfg!(windows) {
3256             symlink_dir(r"..\d\e", &c).unwrap();
3257             symlink_file(r"..\f", &e).unwrap();
3258         }
3259
3260         assert_eq!(fs::canonicalize(&c).unwrap(), f);
3261         assert_eq!(fs::canonicalize(&e).unwrap(), f);
3262     }
3263
3264     #[test]
3265     fn dir_entry_methods() {
3266         let tmpdir = tmpdir();
3267
3268         fs::create_dir_all(&tmpdir.join("a")).unwrap();
3269         File::create(&tmpdir.join("b")).unwrap();
3270
3271         for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
3272             let fname = file.file_name();
3273             match fname.to_str() {
3274                 Some("a") => {
3275                     assert!(file.file_type().unwrap().is_dir());
3276                     assert!(file.metadata().unwrap().is_dir());
3277                 }
3278                 Some("b") => {
3279                     assert!(file.file_type().unwrap().is_file());
3280                     assert!(file.metadata().unwrap().is_file());
3281                 }
3282                 f => panic!("unknown file name: {:?}", f),
3283             }
3284         }
3285     }
3286
3287     #[test]
3288     fn dir_entry_debug() {
3289         let tmpdir = tmpdir();
3290         File::create(&tmpdir.join("b")).unwrap();
3291         let mut read_dir = tmpdir.path().read_dir().unwrap();
3292         let dir_entry = read_dir.next().unwrap().unwrap();
3293         let actual = format!("{:?}", dir_entry);
3294         let expected = format!("DirEntry({:?})", dir_entry.0.path());
3295         assert_eq!(actual, expected);
3296     }
3297
3298     #[test]
3299     fn read_dir_not_found() {
3300         let res = fs::read_dir("/path/that/does/not/exist");
3301         assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
3302     }
3303
3304     #[test]
3305     fn create_dir_all_with_junctions() {
3306         let tmpdir = tmpdir();
3307         let target = tmpdir.join("target");
3308
3309         let junction = tmpdir.join("junction");
3310         let b = junction.join("a/b");
3311
3312         let link = tmpdir.join("link");
3313         let d = link.join("c/d");
3314
3315         fs::create_dir(&target).unwrap();
3316
3317         check!(symlink_junction(&target, &junction));
3318         check!(fs::create_dir_all(&b));
3319         // the junction itself is not a directory, but `is_dir()` on a Path
3320         // follows links
3321         assert!(junction.is_dir());
3322         assert!(b.exists());
3323
3324         if !got_symlink_permission(&tmpdir) { return };
3325         check!(symlink_dir(&target, &link));
3326         check!(fs::create_dir_all(&d));
3327         assert!(link.is_dir());
3328         assert!(d.exists());
3329     }
3330
3331     #[test]
3332     fn metadata_access_times() {
3333         let tmpdir = tmpdir();
3334
3335         let b = tmpdir.join("b");
3336         File::create(&b).unwrap();
3337
3338         let a = check!(fs::metadata(&tmpdir.path()));
3339         let b = check!(fs::metadata(&b));
3340
3341         assert_eq!(check!(a.accessed()), check!(a.accessed()));
3342         assert_eq!(check!(a.modified()), check!(a.modified()));
3343         assert_eq!(check!(b.accessed()), check!(b.modified()));
3344
3345         if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3346             check!(a.created());
3347             check!(b.created());
3348         }
3349     }
3350 }