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