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