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