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