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.
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.
11 //! Filesystem manipulation operations.
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`.
18 #![stable(feature = "rust1", since = "1.0.0")]
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};
28 /// A reference to an open file on the filesystem.
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.
34 /// Files are automatically closed when they go out of scope.
38 /// Create a new file and write bytes to it:
41 /// use std::fs::File;
42 /// use std::io::prelude::*;
44 /// # fn foo() -> std::io::Result<()> {
45 /// let mut file = File::create("foo.txt")?;
46 /// file.write_all(b"Hello, world!")?;
51 /// Read the contents of a file into a [`String`]:
54 /// use std::fs::File;
55 /// use std::io::prelude::*;
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!");
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>`]:
70 /// use std::fs::File;
71 /// use std::io::BufReader;
72 /// use std::io::prelude::*;
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!");
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")]
93 /// Metadata information about a file.
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
100 /// [`metadata`]: fn.metadata.html
101 /// [`symlink_metadata`]: fn.symlink_metadata.html
102 #[stable(feature = "rust1", since = "1.0.0")]
104 pub struct Metadata(fs_imp::FileAttr);
106 /// Iterator over the entries in a directory.
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
115 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
116 /// IO error during iteration.
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")]
124 pub struct ReadDir(fs_imp::ReadDir);
126 /// Entries returned by the [`ReadDir`] iterator.
128 /// [`ReadDir`]: struct.ReadDir.html
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);
136 /// Options and flags which can be used to configure how a file is opened.
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
143 /// [`File`]: struct.File.html
144 /// [`File::open`]: struct.File.html#method.open
145 /// [`File::create`]: struct.File.html#method.create
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
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
160 /// Opening a file to read:
163 /// use std::fs::OpenOptions;
165 /// let file = OpenOptions::new().read(true).open("foo.txt");
168 /// Opening a file for both reading and writing, as well as creating it if it
172 /// use std::fs::OpenOptions;
174 /// let file = OpenOptions::new()
178 /// .open("foo.txt");
180 #[derive(Clone, Debug)]
181 #[stable(feature = "rust1", since = "1.0.0")]
182 pub struct OpenOptions(fs_imp::OpenOptions);
184 /// Representation of the various permissions on a file.
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.
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);
196 /// A structure representing a type of file with accessors for each file type.
197 /// It is returned by [`Metadata::file_type`] method.
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);
204 /// A builder used to create directories in various manners.
206 /// This builder also supports platform-specific options.
207 #[stable(feature = "dir_builder", since = "1.6.0")]
209 pub struct DirBuilder {
210 inner: fs_imp::DirBuilder,
215 /// Attempts to open a file in read-only mode.
217 /// See the [`OpenOptions::open`] method for more details.
221 /// This function will return an error if `path` does not already exist.
222 /// Other errors may also be returned according to [`OpenOptions::open`].
224 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
229 /// use std::fs::File;
231 /// # fn foo() -> std::io::Result<()> {
232 /// let mut f = File::open("foo.txt")?;
236 #[stable(feature = "rust1", since = "1.0.0")]
237 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
238 OpenOptions::new().read(true).open(path.as_ref())
241 /// Opens a file in write-only mode.
243 /// This function will create a file if it does not exist,
244 /// and will truncate it if it does.
246 /// See the [`OpenOptions::open`] function for more details.
248 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
253 /// use std::fs::File;
255 /// # fn foo() -> std::io::Result<()> {
256 /// let mut f = File::create("foo.txt")?;
260 #[stable(feature = "rust1", since = "1.0.0")]
261 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
262 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
265 /// Attempts to sync all OS-internal metadata to disk.
267 /// This function will attempt to ensure that all in-core data reaches the
268 /// filesystem before returning.
273 /// use std::fs::File;
274 /// use std::io::prelude::*;
276 /// # fn foo() -> std::io::Result<()> {
277 /// let mut f = File::create("foo.txt")?;
278 /// f.write_all(b"Hello, world!")?;
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub fn sync_all(&self) -> io::Result<()> {
289 /// This function is similar to [`sync_all`], except that it may not
290 /// synchronize file metadata to the filesystem.
292 /// This is intended for use cases that must synchronize content, but don't
293 /// need the metadata on disk. The goal of this method is to reduce disk
296 /// Note that some platforms may simply implement this in terms of
299 /// [`sync_all`]: struct.File.html#method.sync_all
304 /// use std::fs::File;
305 /// use std::io::prelude::*;
307 /// # fn foo() -> std::io::Result<()> {
308 /// let mut f = File::create("foo.txt")?;
309 /// f.write_all(b"Hello, world!")?;
315 #[stable(feature = "rust1", since = "1.0.0")]
316 pub fn sync_data(&self) -> io::Result<()> {
317 self.inner.datasync()
320 /// Truncates or extends the underlying file, updating the size of
321 /// this file to become `size`.
323 /// If the `size` is less than the current file's size, then the file will
324 /// be shrunk. If it is greater than the current file's size, then the file
325 /// will be extended to `size` and have all of the intermediate data filled
330 /// This function will return an error if the file is not opened for writing.
335 /// use std::fs::File;
337 /// # fn foo() -> std::io::Result<()> {
338 /// let mut f = File::create("foo.txt")?;
343 #[stable(feature = "rust1", since = "1.0.0")]
344 pub fn set_len(&self, size: u64) -> io::Result<()> {
345 self.inner.truncate(size)
348 /// Queries metadata about the underlying file.
353 /// use std::fs::File;
355 /// # fn foo() -> std::io::Result<()> {
356 /// let mut f = File::open("foo.txt")?;
357 /// let metadata = f.metadata()?;
361 #[stable(feature = "rust1", since = "1.0.0")]
362 pub fn metadata(&self) -> io::Result<Metadata> {
363 self.inner.file_attr().map(Metadata)
366 /// Creates a new independently owned handle to the underlying file.
368 /// The returned `File` is a reference to the same state that this object
369 /// references. Both handles will read and write with the same cursor
375 /// use std::fs::File;
377 /// # fn foo() -> std::io::Result<()> {
378 /// let mut f = File::open("foo.txt")?;
379 /// let file_copy = f.try_clone()?;
383 #[stable(feature = "file_try_clone", since = "1.9.0")]
384 pub fn try_clone(&self) -> io::Result<File> {
386 inner: self.inner.duplicate()?
390 /// Changes the permissions on the underlying file.
392 /// # Platform-specific behavior
394 /// This function currently corresponds to the `fchmod` function on Unix and
395 /// the `SetFileInformationByHandle` function on Windows. Note that, this
396 /// [may change in the future][changes].
398 /// [changes]: ../io/index.html#platform-specific-behavior
402 /// This function will return an error if the user lacks permission change
403 /// attributes on the underlying file. It may also return an error in other
404 /// os-specific unspecified cases.
409 /// # fn foo() -> std::io::Result<()> {
410 /// use std::fs::File;
412 /// let file = File::open("foo.txt")?;
413 /// let mut perms = file.metadata()?.permissions();
414 /// perms.set_readonly(true);
415 /// file.set_permissions(perms)?;
419 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
420 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
421 self.inner.set_permissions(perm.0)
425 impl AsInner<fs_imp::File> for File {
426 fn as_inner(&self) -> &fs_imp::File { &self.inner }
428 impl FromInner<fs_imp::File> for File {
429 fn from_inner(f: fs_imp::File) -> File {
433 impl IntoInner<fs_imp::File> for File {
434 fn into_inner(self) -> fs_imp::File {
439 #[stable(feature = "rust1", since = "1.0.0")]
440 impl fmt::Debug for File {
441 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
446 #[stable(feature = "rust1", since = "1.0.0")]
448 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
453 unsafe fn initializer(&self) -> Initializer {
457 #[stable(feature = "rust1", since = "1.0.0")]
458 impl Write for File {
459 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
460 self.inner.write(buf)
462 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
464 #[stable(feature = "rust1", since = "1.0.0")]
466 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl<'a> Read for &'a File {
472 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
477 unsafe fn initializer(&self) -> Initializer {
481 #[stable(feature = "rust1", since = "1.0.0")]
482 impl<'a> Write for &'a File {
483 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
484 self.inner.write(buf)
486 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
488 #[stable(feature = "rust1", since = "1.0.0")]
489 impl<'a> Seek for &'a File {
490 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
496 /// Creates a blank new set of options ready for configuration.
498 /// All options are initially set to `false`.
503 /// use std::fs::OpenOptions;
505 /// let mut options = OpenOptions::new();
506 /// let file = options.read(true).open("foo.txt");
508 #[stable(feature = "rust1", since = "1.0.0")]
509 pub fn new() -> OpenOptions {
510 OpenOptions(fs_imp::OpenOptions::new())
513 /// Sets the option for read access.
515 /// This option, when true, will indicate that the file should be
516 /// `read`-able if opened.
521 /// use std::fs::OpenOptions;
523 /// let file = OpenOptions::new().read(true).open("foo.txt");
525 #[stable(feature = "rust1", since = "1.0.0")]
526 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
527 self.0.read(read); self
530 /// Sets the option for write access.
532 /// This option, when true, will indicate that the file should be
533 /// `write`-able if opened.
535 /// If the file already exists, any write calls on it will overwrite its
536 /// contents, without truncating it.
541 /// use std::fs::OpenOptions;
543 /// let file = OpenOptions::new().write(true).open("foo.txt");
545 #[stable(feature = "rust1", since = "1.0.0")]
546 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
547 self.0.write(write); self
550 /// Sets the option for the append mode.
552 /// This option, when true, means that writes will append to a file instead
553 /// of overwriting previous contents.
554 /// Note that setting `.write(true).append(true)` has the same effect as
555 /// setting only `.append(true)`.
557 /// For most filesystems, the operating system guarantees that all writes are
558 /// atomic: no writes get mangled because another process writes at the same
561 /// One maybe obvious note when using append-mode: make sure that all data
562 /// that belongs together is written to the file in one operation. This
563 /// can be done by concatenating strings before passing them to [`write()`],
564 /// or using a buffered writer (with a buffer of adequate size),
565 /// and calling [`flush()`] when the message is complete.
567 /// If a file is opened with both read and append access, beware that after
568 /// opening, and after every write, the position for reading may be set at the
569 /// end of the file. So, before writing, save the current position (using
570 /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`, and restore it before the next read.
572 /// [`write()`]: ../../std/fs/struct.File.html#method.write
573 /// [`flush()`]: ../../std/fs/struct.File.html#method.flush
574 /// [`seek`]: ../../std/fs/struct.File.html#method.seek
575 /// [`SeekFrom`]: ../../std/io/enum.SeekFrom.html
576 /// [`Current`]: ../../std/io/enum.SeekFrom.html#variant.Current
581 /// use std::fs::OpenOptions;
583 /// let file = OpenOptions::new().append(true).open("foo.txt");
585 #[stable(feature = "rust1", since = "1.0.0")]
586 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
587 self.0.append(append); self
590 /// Sets the option for truncating a previous file.
592 /// If a file is successfully opened with this option set it will truncate
593 /// the file to 0 length if it already exists.
595 /// The file must be opened with write access for truncate to work.
600 /// use std::fs::OpenOptions;
602 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
604 #[stable(feature = "rust1", since = "1.0.0")]
605 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
606 self.0.truncate(truncate); self
609 /// Sets the option for creating a new file.
611 /// This option indicates whether a new file will be created if the file
612 /// does not yet already exist.
614 /// In order for the file to be created, [`write`] or [`append`] access must
617 /// [`write`]: #method.write
618 /// [`append`]: #method.append
623 /// use std::fs::OpenOptions;
625 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
627 #[stable(feature = "rust1", since = "1.0.0")]
628 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
629 self.0.create(create); self
632 /// Sets the option to always create a new file.
634 /// This option indicates whether a new file will be created.
635 /// No file is allowed to exist at the target location, also no (dangling)
638 /// This option is useful because it is atomic. Otherwise between checking
639 /// whether a file exists and creating a new one, the file may have been
640 /// created by another process (a TOCTOU race condition / attack).
642 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
645 /// The file must be opened with write or append access in order to create
648 /// [`.create()`]: #method.create
649 /// [`.truncate()`]: #method.truncate
654 /// use std::fs::OpenOptions;
656 /// let file = OpenOptions::new().write(true)
657 /// .create_new(true)
658 /// .open("foo.txt");
660 #[stable(feature = "expand_open_options2", since = "1.9.0")]
661 pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
662 self.0.create_new(create_new); self
665 /// Opens a file at `path` with the options specified by `self`.
669 /// This function will return an error under a number of different
670 /// circumstances. Some of these error conditions are listed here, together
671 /// with their [`ErrorKind`]. The mapping to [`ErrorKind`]s is not part of
672 /// the compatibility contract of the function, especially the `Other` kind
673 /// might change to more specific kinds in the future.
675 /// * [`NotFound`]: The specified file does not exist and neither `create`
676 /// or `create_new` is set.
677 /// * [`NotFound`]: One of the directory components of the file path does
679 /// * [`PermissionDenied`]: The user lacks permission to get the specified
680 /// access rights for the file.
681 /// * [`PermissionDenied`]: The user lacks permission to open one of the
682 /// directory components of the specified path.
683 /// * [`AlreadyExists`]: `create_new` was specified and the file already
685 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
686 /// without write access, no access mode set, etc.).
687 /// * [`Other`]: One of the directory components of the specified file path
688 /// was not, in fact, a directory.
689 /// * [`Other`]: Filesystem-level errors: full disk, write permission
690 /// requested on a read-only file system, exceeded disk quota, too many
691 /// open files, too long filename, too many symbolic links in the
692 /// specified path (Unix-like systems only), etc.
697 /// use std::fs::OpenOptions;
699 /// let file = OpenOptions::new().open("foo.txt");
702 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
703 /// [`AlreadyExists`]: ../io/enum.ErrorKind.html#variant.AlreadyExists
704 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
705 /// [`NotFound`]: ../io/enum.ErrorKind.html#variant.NotFound
706 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
707 /// [`PermissionDenied`]: ../io/enum.ErrorKind.html#variant.PermissionDenied
708 #[stable(feature = "rust1", since = "1.0.0")]
709 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
710 self._open(path.as_ref())
713 fn _open(&self, path: &Path) -> io::Result<File> {
714 let inner = fs_imp::File::open(path, &self.0)?;
715 Ok(File { inner: inner })
719 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
720 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
724 /// Returns the file type for this metadata.
729 /// # fn foo() -> std::io::Result<()> {
732 /// let metadata = fs::metadata("foo.txt")?;
734 /// println!("{:?}", metadata.file_type());
738 #[stable(feature = "file_type", since = "1.1.0")]
739 pub fn file_type(&self) -> FileType {
740 FileType(self.0.file_type())
743 /// Returns whether this metadata is for a directory.
748 /// # fn foo() -> std::io::Result<()> {
751 /// let metadata = fs::metadata("foo.txt")?;
753 /// assert!(!metadata.is_dir());
757 #[stable(feature = "rust1", since = "1.0.0")]
758 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
760 /// Returns whether this metadata is for a regular file.
765 /// # fn foo() -> std::io::Result<()> {
768 /// let metadata = fs::metadata("foo.txt")?;
770 /// assert!(metadata.is_file());
774 #[stable(feature = "rust1", since = "1.0.0")]
775 pub fn is_file(&self) -> bool { self.file_type().is_file() }
777 /// Returns the size of the file, in bytes, this metadata is for.
782 /// # fn foo() -> std::io::Result<()> {
785 /// let metadata = fs::metadata("foo.txt")?;
787 /// assert_eq!(0, metadata.len());
791 #[stable(feature = "rust1", since = "1.0.0")]
792 pub fn len(&self) -> u64 { self.0.size() }
794 /// Returns the permissions of the file this metadata is for.
799 /// # fn foo() -> std::io::Result<()> {
802 /// let metadata = fs::metadata("foo.txt")?;
804 /// assert!(!metadata.permissions().readonly());
808 #[stable(feature = "rust1", since = "1.0.0")]
809 pub fn permissions(&self) -> Permissions {
810 Permissions(self.0.perm())
813 /// Returns the last modification time listed in this metadata.
815 /// The returned value corresponds to the `mtime` field of `stat` on Unix
816 /// platforms and the `ftLastWriteTime` field on Windows platforms.
820 /// This field may not be available on all platforms, and will return an
821 /// `Err` on platforms where it is not available.
826 /// # fn foo() -> std::io::Result<()> {
829 /// let metadata = fs::metadata("foo.txt")?;
831 /// if let Ok(time) = metadata.modified() {
832 /// println!("{:?}", time);
834 /// println!("Not supported on this platform");
839 #[stable(feature = "fs_time", since = "1.10.0")]
840 pub fn modified(&self) -> io::Result<SystemTime> {
841 self.0.modified().map(FromInner::from_inner)
844 /// Returns the last access time of this metadata.
846 /// The returned value corresponds to the `atime` field of `stat` on Unix
847 /// platforms and the `ftLastAccessTime` field on Windows platforms.
849 /// Note that not all platforms will keep this field update in a file's
850 /// metadata, for example Windows has an option to disable updating this
851 /// time when files are accessed and Linux similarly has `noatime`.
855 /// This field may not be available on all platforms, and will return an
856 /// `Err` on platforms where it is not available.
861 /// # fn foo() -> std::io::Result<()> {
864 /// let metadata = fs::metadata("foo.txt")?;
866 /// if let Ok(time) = metadata.accessed() {
867 /// println!("{:?}", time);
869 /// println!("Not supported on this platform");
874 #[stable(feature = "fs_time", since = "1.10.0")]
875 pub fn accessed(&self) -> io::Result<SystemTime> {
876 self.0.accessed().map(FromInner::from_inner)
879 /// Returns the creation time listed in the this metadata.
881 /// The returned value corresponds to the `birthtime` field of `stat` on
882 /// Unix platforms and the `ftCreationTime` field on Windows platforms.
886 /// This field may not be available on all platforms, and will return an
887 /// `Err` on platforms where it is not available.
892 /// # fn foo() -> std::io::Result<()> {
895 /// let metadata = fs::metadata("foo.txt")?;
897 /// if let Ok(time) = metadata.created() {
898 /// println!("{:?}", time);
900 /// println!("Not supported on this platform");
905 #[stable(feature = "fs_time", since = "1.10.0")]
906 pub fn created(&self) -> io::Result<SystemTime> {
907 self.0.created().map(FromInner::from_inner)
911 #[stable(feature = "std_debug", since = "1.16.0")]
912 impl fmt::Debug for Metadata {
913 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
914 f.debug_struct("Metadata")
915 .field("file_type", &self.file_type())
916 .field("is_dir", &self.is_dir())
917 .field("is_file", &self.is_file())
918 .field("permissions", &self.permissions())
919 .field("modified", &self.modified())
920 .field("accessed", &self.accessed())
921 .field("created", &self.created())
926 impl AsInner<fs_imp::FileAttr> for Metadata {
927 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
931 /// Returns whether these permissions describe a readonly (unwritable) file.
936 /// use std::fs::File;
938 /// # fn foo() -> std::io::Result<()> {
939 /// let mut f = File::create("foo.txt")?;
940 /// let metadata = f.metadata()?;
942 /// assert_eq!(false, metadata.permissions().readonly());
946 #[stable(feature = "rust1", since = "1.0.0")]
947 pub fn readonly(&self) -> bool { self.0.readonly() }
949 /// Modifies the readonly flag for this set of permissions. If the
950 /// `readonly` argument is `true`, using the resulting `Permission` will
951 /// update file permissions to forbid writing. Conversely, if it's `false`,
952 /// using the resulting `Permission` will update file permissions to allow
955 /// This operation does **not** modify the filesystem. To modify the
956 /// filesystem use the `fs::set_permissions` function.
961 /// use std::fs::File;
963 /// # fn foo() -> std::io::Result<()> {
964 /// let f = File::create("foo.txt")?;
965 /// let metadata = f.metadata()?;
966 /// let mut permissions = metadata.permissions();
968 /// permissions.set_readonly(true);
970 /// // filesystem doesn't change
971 /// assert_eq!(false, metadata.permissions().readonly());
973 /// // just this particular `permissions`.
974 /// assert_eq!(true, permissions.readonly());
978 #[stable(feature = "rust1", since = "1.0.0")]
979 pub fn set_readonly(&mut self, readonly: bool) {
980 self.0.set_readonly(readonly)
985 /// Test whether this file type represents a directory.
990 /// # fn foo() -> std::io::Result<()> {
993 /// let metadata = fs::metadata("foo.txt")?;
994 /// let file_type = metadata.file_type();
996 /// assert_eq!(file_type.is_dir(), false);
1000 #[stable(feature = "file_type", since = "1.1.0")]
1001 pub fn is_dir(&self) -> bool { self.0.is_dir() }
1003 /// Test whether this file type represents a regular file.
1008 /// # fn foo() -> std::io::Result<()> {
1011 /// let metadata = fs::metadata("foo.txt")?;
1012 /// let file_type = metadata.file_type();
1014 /// assert_eq!(file_type.is_file(), true);
1018 #[stable(feature = "file_type", since = "1.1.0")]
1019 pub fn is_file(&self) -> bool { self.0.is_file() }
1021 /// Test whether this file type represents a symbolic link.
1023 /// The underlying [`Metadata`] struct needs to be retrieved
1024 /// with the [`fs::symlink_metadata`] function and not the
1025 /// [`fs::metadata`] function. The [`fs::metadata`] function
1026 /// follows symbolic links, so [`is_symlink`] would always
1027 /// return false for the target file.
1029 /// [`Metadata`]: struct.Metadata.html
1030 /// [`fs::metadata`]: fn.metadata.html
1031 /// [`fs::symlink_metadata`]: fn.symlink_metadata.html
1032 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1037 /// # fn foo() -> std::io::Result<()> {
1040 /// let metadata = fs::symlink_metadata("foo.txt")?;
1041 /// let file_type = metadata.file_type();
1043 /// assert_eq!(file_type.is_symlink(), false);
1047 #[stable(feature = "file_type", since = "1.1.0")]
1048 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
1051 impl AsInner<fs_imp::FileType> for FileType {
1052 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
1055 impl FromInner<fs_imp::FilePermissions> for Permissions {
1056 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1061 impl AsInner<fs_imp::FilePermissions> for Permissions {
1062 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
1065 #[stable(feature = "rust1", since = "1.0.0")]
1066 impl Iterator for ReadDir {
1067 type Item = io::Result<DirEntry>;
1069 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1070 self.0.next().map(|entry| entry.map(DirEntry))
1075 /// Returns the full path to the file that this entry represents.
1077 /// The full path is created by joining the original path to `read_dir`
1078 /// with the filename of this entry.
1084 /// # fn foo() -> std::io::Result<()> {
1085 /// for entry in fs::read_dir(".")? {
1086 /// let dir = entry?;
1087 /// println!("{:?}", dir.path());
1093 /// This prints output like:
1096 /// "./whatever.txt"
1098 /// "./hello_world.rs"
1101 /// The exact text, of course, depends on what files you have in `.`.
1102 #[stable(feature = "rust1", since = "1.0.0")]
1103 pub fn path(&self) -> PathBuf { self.0.path() }
1105 /// Return the metadata for the file that this entry points at.
1107 /// This function will not traverse symlinks if this entry points at a
1110 /// # Platform-specific behavior
1112 /// On Windows this function is cheap to call (no extra system calls
1113 /// needed), but on Unix platforms this function is the equivalent of
1114 /// calling `symlink_metadata` on the path.
1121 /// if let Ok(entries) = fs::read_dir(".") {
1122 /// for entry in entries {
1123 /// if let Ok(entry) = entry {
1124 /// // Here, `entry` is a `DirEntry`.
1125 /// if let Ok(metadata) = entry.metadata() {
1126 /// // Now let's show our entry's permissions!
1127 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1129 /// println!("Couldn't get metadata for {:?}", entry.path());
1135 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1136 pub fn metadata(&self) -> io::Result<Metadata> {
1137 self.0.metadata().map(Metadata)
1140 /// Return the file type for the file that this entry points at.
1142 /// This function will not traverse symlinks if this entry points at a
1145 /// # Platform-specific behavior
1147 /// On Windows and most Unix platforms this function is free (no extra
1148 /// system calls needed), but some Unix platforms may require the equivalent
1149 /// call to `symlink_metadata` to learn about the target file type.
1156 /// if let Ok(entries) = fs::read_dir(".") {
1157 /// for entry in entries {
1158 /// if let Ok(entry) = entry {
1159 /// // Here, `entry` is a `DirEntry`.
1160 /// if let Ok(file_type) = entry.file_type() {
1161 /// // Now let's show our entry's file type!
1162 /// println!("{:?}: {:?}", entry.path(), file_type);
1164 /// println!("Couldn't get file type for {:?}", entry.path());
1170 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1171 pub fn file_type(&self) -> io::Result<FileType> {
1172 self.0.file_type().map(FileType)
1175 /// Returns the bare file name of this directory entry without any other
1176 /// leading path component.
1183 /// if let Ok(entries) = fs::read_dir(".") {
1184 /// for entry in entries {
1185 /// if let Ok(entry) = entry {
1186 /// // Here, `entry` is a `DirEntry`.
1187 /// println!("{:?}", entry.file_name());
1192 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1193 pub fn file_name(&self) -> OsString {
1198 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1199 impl fmt::Debug for DirEntry {
1200 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1201 f.debug_tuple("DirEntry")
1202 .field(&self.path())
1207 impl AsInner<fs_imp::DirEntry> for DirEntry {
1208 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
1211 /// Removes a file from the filesystem.
1213 /// Note that there is no
1214 /// guarantee that the file is immediately deleted (e.g. depending on
1215 /// platform, other open file descriptors may prevent immediate removal).
1217 /// # Platform-specific behavior
1219 /// This function currently corresponds to the `unlink` function on Unix
1220 /// and the `DeleteFile` function on Windows.
1221 /// Note that, this [may change in the future][changes].
1223 /// [changes]: ../io/index.html#platform-specific-behavior
1227 /// This function will return an error in the following situations, but is not
1228 /// limited to just these cases:
1230 /// * `path` points to a directory.
1231 /// * The user lacks permissions to remove the file.
1238 /// # fn foo() -> std::io::Result<()> {
1239 /// fs::remove_file("a.txt")?;
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1245 fs_imp::unlink(path.as_ref())
1248 /// Given a path, query the file system to get information about a file,
1251 /// This function will traverse symbolic links to query information about the
1252 /// destination file.
1254 /// # Platform-specific behavior
1256 /// This function currently corresponds to the `stat` function on Unix
1257 /// and the `GetFileAttributesEx` function on Windows.
1258 /// Note that, this [may change in the future][changes].
1260 /// [changes]: ../io/index.html#platform-specific-behavior
1264 /// This function will return an error in the following situations, but is not
1265 /// limited to just these cases:
1267 /// * The user lacks permissions to perform `metadata` call on `path`.
1268 /// * `path` does not exist.
1273 /// # fn foo() -> std::io::Result<()> {
1276 /// let attr = fs::metadata("/some/file/path.txt")?;
1277 /// // inspect attr ...
1281 #[stable(feature = "rust1", since = "1.0.0")]
1282 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1283 fs_imp::stat(path.as_ref()).map(Metadata)
1286 /// Query the metadata about a file without following symlinks.
1288 /// # Platform-specific behavior
1290 /// This function currently corresponds to the `lstat` function on Unix
1291 /// and the `GetFileAttributesEx` function on Windows.
1292 /// Note that, this [may change in the future][changes].
1294 /// [changes]: ../io/index.html#platform-specific-behavior
1298 /// This function will return an error in the following situations, but is not
1299 /// limited to just these cases:
1301 /// * The user lacks permissions to perform `metadata` call on `path`.
1302 /// * `path` does not exist.
1307 /// # fn foo() -> std::io::Result<()> {
1310 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1311 /// // inspect attr ...
1315 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1316 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1317 fs_imp::lstat(path.as_ref()).map(Metadata)
1320 /// Rename a file or directory to a new name, replacing the original file if
1321 /// `to` already exists.
1323 /// This will not work if the new name is on a different mount point.
1325 /// # Platform-specific behavior
1327 /// This function currently corresponds to the `rename` function on Unix
1328 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1330 /// Because of this, the behavior when both `from` and `to` exist differs. On
1331 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1332 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1333 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1335 /// Note that, this [may change in the future][changes].
1337 /// [changes]: ../io/index.html#platform-specific-behavior
1341 /// This function will return an error in the following situations, but is not
1342 /// limited to just these cases:
1344 /// * `from` does not exist.
1345 /// * The user lacks permissions to view contents.
1346 /// * `from` and `to` are on separate filesystems.
1353 /// # fn foo() -> std::io::Result<()> {
1354 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1360 fs_imp::rename(from.as_ref(), to.as_ref())
1363 /// Copies the contents of one file to another. This function will also
1364 /// copy the permission bits of the original file to the destination file.
1366 /// This function will **overwrite** the contents of `to`.
1368 /// Note that if `from` and `to` both point to the same file, then the file
1369 /// will likely get truncated by this operation.
1371 /// On success, the total number of bytes copied is returned.
1373 /// # Platform-specific behavior
1375 /// This function currently corresponds to the `open` function in Unix
1376 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1377 /// `O_CLOEXEC` is set for returned file descriptors.
1378 /// On Windows, this function currently corresponds to `CopyFileEx`.
1379 /// Note that, this [may change in the future][changes].
1381 /// [changes]: ../io/index.html#platform-specific-behavior
1385 /// This function will return an error in the following situations, but is not
1386 /// limited to just these cases:
1388 /// * The `from` path is not a file.
1389 /// * The `from` file does not exist.
1390 /// * The current process does not have the permission rights to access
1391 /// `from` or write `to`.
1398 /// # fn foo() -> std::io::Result<()> {
1399 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1404 fs_imp::copy(from.as_ref(), to.as_ref())
1407 /// Creates a new hard link on the filesystem.
1409 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1410 /// often require these two paths to both be located on the same filesystem.
1412 /// # Platform-specific behavior
1414 /// This function currently corresponds to the `link` function on Unix
1415 /// and the `CreateHardLink` function on Windows.
1416 /// Note that, this [may change in the future][changes].
1418 /// [changes]: ../io/index.html#platform-specific-behavior
1422 /// This function will return an error in the following situations, but is not
1423 /// limited to just these cases:
1425 /// * The `src` path is not a file or doesn't exist.
1432 /// # fn foo() -> std::io::Result<()> {
1433 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1437 #[stable(feature = "rust1", since = "1.0.0")]
1438 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1439 fs_imp::link(src.as_ref(), dst.as_ref())
1442 /// Creates a new symbolic link on the filesystem.
1444 /// The `dst` path will be a symbolic link pointing to the `src` path.
1445 /// On Windows, this will be a file symlink, not a directory symlink;
1446 /// for this reason, the platform-specific `std::os::unix::fs::symlink`
1447 /// and `std::os::windows::fs::{symlink_file, symlink_dir}` should be
1448 /// used instead to make the intent explicit.
1455 /// # fn foo() -> std::io::Result<()> {
1456 /// fs::soft_link("a.txt", "b.txt")?;
1460 #[stable(feature = "rust1", since = "1.0.0")]
1461 #[rustc_deprecated(since = "1.1.0",
1462 reason = "replaced with std::os::unix::fs::symlink and \
1463 std::os::windows::fs::{symlink_file, symlink_dir}")]
1464 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1465 fs_imp::symlink(src.as_ref(), dst.as_ref())
1468 /// Reads a symbolic link, returning the file that the link points to.
1470 /// # Platform-specific behavior
1472 /// This function currently corresponds to the `readlink` function on Unix
1473 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1474 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1475 /// Note that, this [may change in the future][changes].
1477 /// [changes]: ../io/index.html#platform-specific-behavior
1481 /// This function will return an error in the following situations, but is not
1482 /// limited to just these cases:
1484 /// * `path` is not a symbolic link.
1485 /// * `path` does not exist.
1492 /// # fn foo() -> std::io::Result<()> {
1493 /// let path = fs::read_link("a.txt")?;
1497 #[stable(feature = "rust1", since = "1.0.0")]
1498 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1499 fs_imp::readlink(path.as_ref())
1502 /// Returns the canonical form of a path with all intermediate components
1503 /// normalized and symbolic links resolved.
1505 /// # Platform-specific behavior
1507 /// This function currently corresponds to the `realpath` function on Unix
1508 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1509 /// Note that, this [may change in the future][changes].
1511 /// [changes]: ../io/index.html#platform-specific-behavior
1515 /// This function will return an error in the following situations, but is not
1516 /// limited to just these cases:
1518 /// * `path` does not exist.
1519 /// * A component in path is not a directory.
1526 /// # fn foo() -> std::io::Result<()> {
1527 /// let path = fs::canonicalize("../a/../foo.txt")?;
1531 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1532 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1533 fs_imp::canonicalize(path.as_ref())
1536 /// Creates a new, empty directory at the provided path
1538 /// # Platform-specific behavior
1540 /// This function currently corresponds to the `mkdir` function on Unix
1541 /// and the `CreateDirectory` function on Windows.
1542 /// Note that, this [may change in the future][changes].
1544 /// [changes]: ../io/index.html#platform-specific-behavior
1548 /// This function will return an error in the following situations, but is not
1549 /// limited to just these cases:
1551 /// * User lacks permissions to create directory at `path`.
1552 /// * `path` already exists.
1559 /// # fn foo() -> std::io::Result<()> {
1560 /// fs::create_dir("/some/dir")?;
1564 #[stable(feature = "rust1", since = "1.0.0")]
1565 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1566 DirBuilder::new().create(path.as_ref())
1569 /// Recursively create a directory and all of its parent components if they
1572 /// # Platform-specific behavior
1574 /// This function currently corresponds to the `mkdir` function on Unix
1575 /// and the `CreateDirectory` function on Windows.
1576 /// Note that, this [may change in the future][changes].
1578 /// [changes]: ../io/index.html#platform-specific-behavior
1582 /// This function will return an error in the following situations, but is not
1583 /// limited to just these cases:
1585 /// * If any directory in the path specified by `path`
1586 /// does not already exist and it could not be created otherwise. The specific
1587 /// error conditions for when a directory is being created (after it is
1588 /// determined to not exist) are outlined by `fs::create_dir`.
1590 /// Notable exception is made for situations where any of the directories
1591 /// specified in the `path` could not be created as it was being created concurrently.
1592 /// Such cases are considered success. In other words: calling `create_dir_all`
1593 /// concurrently from multiple threads or processes is guaranteed to not fail
1594 /// due to race itself.
1601 /// # fn foo() -> std::io::Result<()> {
1602 /// fs::create_dir_all("/some/dir")?;
1606 #[stable(feature = "rust1", since = "1.0.0")]
1607 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1608 DirBuilder::new().recursive(true).create(path.as_ref())
1611 /// Removes an existing, empty directory.
1613 /// # Platform-specific behavior
1615 /// This function currently corresponds to the `rmdir` function on Unix
1616 /// and the `RemoveDirectory` function on Windows.
1617 /// Note that, this [may change in the future][changes].
1619 /// [changes]: ../io/index.html#platform-specific-behavior
1623 /// This function will return an error in the following situations, but is not
1624 /// limited to just these cases:
1626 /// * The user lacks permissions to remove the directory at the provided `path`.
1627 /// * The directory isn't empty.
1634 /// # fn foo() -> std::io::Result<()> {
1635 /// fs::remove_dir("/some/dir")?;
1639 #[stable(feature = "rust1", since = "1.0.0")]
1640 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1641 fs_imp::rmdir(path.as_ref())
1644 /// Removes a directory at this path, after removing all its contents. Use
1647 /// This function does **not** follow symbolic links and it will simply remove the
1648 /// symbolic link itself.
1650 /// # Platform-specific behavior
1652 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1653 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1655 /// Note that, this [may change in the future][changes].
1657 /// [changes]: ../io/index.html#platform-specific-behavior
1661 /// See `file::remove_file` and `fs::remove_dir`.
1668 /// # fn foo() -> std::io::Result<()> {
1669 /// fs::remove_dir_all("/some/dir")?;
1673 #[stable(feature = "rust1", since = "1.0.0")]
1674 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1675 fs_imp::remove_dir_all(path.as_ref())
1678 /// Returns an iterator over the entries within a directory.
1680 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
1681 /// New errors may be encountered after an iterator is initially constructed.
1683 /// [`io::Result`]: ../io/type.Result.html
1684 /// [`DirEntry`]: struct.DirEntry.html
1686 /// # Platform-specific behavior
1688 /// This function currently corresponds to the `opendir` function on Unix
1689 /// and the `FindFirstFile` function on Windows.
1690 /// Note that, this [may change in the future][changes].
1692 /// [changes]: ../io/index.html#platform-specific-behavior
1696 /// This function will return an error in the following situations, but is not
1697 /// limited to just these cases:
1699 /// * The provided `path` doesn't exist.
1700 /// * The process lacks permissions to view the contents.
1701 /// * The `path` points at a non-directory file.
1707 /// use std::fs::{self, DirEntry};
1708 /// use std::path::Path;
1710 /// // one possible implementation of walking a directory only visiting files
1711 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1712 /// if dir.is_dir() {
1713 /// for entry in fs::read_dir(dir)? {
1714 /// let entry = entry?;
1715 /// let path = entry.path();
1716 /// if path.is_dir() {
1717 /// visit_dirs(&path, cb)?;
1726 #[stable(feature = "rust1", since = "1.0.0")]
1727 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1728 fs_imp::readdir(path.as_ref()).map(ReadDir)
1731 /// Changes the permissions found on a file or a directory.
1733 /// # Platform-specific behavior
1735 /// This function currently corresponds to the `chmod` function on Unix
1736 /// and the `SetFileAttributes` function on Windows.
1737 /// Note that, this [may change in the future][changes].
1739 /// [changes]: ../io/index.html#platform-specific-behavior
1743 /// This function will return an error in the following situations, but is not
1744 /// limited to just these cases:
1746 /// * `path` does not exist.
1747 /// * The user lacks the permission to change attributes of the file.
1752 /// # fn foo() -> std::io::Result<()> {
1755 /// let mut perms = fs::metadata("foo.txt")?.permissions();
1756 /// perms.set_readonly(true);
1757 /// fs::set_permissions("foo.txt", perms)?;
1761 #[stable(feature = "set_permissions", since = "1.1.0")]
1762 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1764 fs_imp::set_perm(path.as_ref(), perm.0)
1768 /// Creates a new set of options with default mode/security settings for all
1769 /// platforms and also non-recursive.
1774 /// use std::fs::DirBuilder;
1776 /// let builder = DirBuilder::new();
1778 #[stable(feature = "dir_builder", since = "1.6.0")]
1779 pub fn new() -> DirBuilder {
1781 inner: fs_imp::DirBuilder::new(),
1786 /// Indicates that directories should be created recursively, creating all
1787 /// parent directories. Parents that do not exist are created with the same
1788 /// security and permissions settings.
1790 /// This option defaults to `false`.
1795 /// use std::fs::DirBuilder;
1797 /// let mut builder = DirBuilder::new();
1798 /// builder.recursive(true);
1800 #[stable(feature = "dir_builder", since = "1.6.0")]
1801 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1802 self.recursive = recursive;
1806 /// Create the specified directory with the options configured in this
1809 /// It is considered an error if the directory already exists unless
1810 /// recursive mode is enabled.
1815 /// use std::fs::{self, DirBuilder};
1817 /// let path = "/tmp/foo/bar/baz";
1818 /// DirBuilder::new()
1819 /// .recursive(true)
1820 /// .create(path).unwrap();
1822 /// assert!(fs::metadata(path).unwrap().is_dir());
1824 #[stable(feature = "dir_builder", since = "1.6.0")]
1825 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1826 self._create(path.as_ref())
1829 fn _create(&self, path: &Path) -> io::Result<()> {
1831 self.create_dir_all(path)
1833 self.inner.mkdir(path)
1837 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1838 if path == Path::new("") {
1842 match self.inner.mkdir(path) {
1843 Ok(()) => return Ok(()),
1844 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
1845 Err(_) if path.is_dir() => return Ok(()),
1846 Err(e) => return Err(e),
1848 match path.parent() {
1849 Some(p) => try!(self.create_dir_all(p)),
1850 None => return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree")),
1852 match self.inner.mkdir(path) {
1854 Err(_) if path.is_dir() => Ok(()),
1860 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1861 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1866 #[cfg(all(test, not(target_os = "emscripten")))]
1870 use fs::{self, File, OpenOptions};
1871 use io::{ErrorKind, SeekFrom};
1873 use rand::{StdRng, Rng};
1875 use sys_common::io::test::{TempDir, tmpdir};
1879 use os::windows::fs::{symlink_dir, symlink_file};
1881 use sys::fs::symlink_junction;
1883 use os::unix::fs::symlink as symlink_dir;
1885 use os::unix::fs::symlink as symlink_file;
1887 use os::unix::fs::symlink as symlink_junction;
1889 macro_rules! check { ($e:expr) => (
1892 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1897 macro_rules! error { ($e:expr, $s:expr) => (
1899 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1900 Err(ref err) => assert!(err.raw_os_error() == Some($s),
1901 format!("`{}` did not have a code of `{}`", err, $s))
1906 macro_rules! error { ($e:expr, $s:expr) => (
1908 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1909 Err(ref err) => assert!(err.to_string().contains($s),
1910 format!("`{}` did not contain `{}`", err, $s))
1914 // Several test fail on windows if the user does not have permission to
1915 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
1916 // disabling these test on Windows, use this function to test whether we
1917 // have permission, and return otherwise. This way, we still don't run these
1918 // tests most of the time, but at least we do if the user has the right
1920 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
1921 if cfg!(unix) { return true }
1922 let link = tmpdir.join("some_hopefully_unique_link_name");
1924 match symlink_file(r"nonexisting_target", link) {
1926 // ERROR_PRIVILEGE_NOT_HELD = 1314
1927 Err(ref err) if err.raw_os_error() == Some(1314) => false,
1933 fn file_test_io_smoke_test() {
1934 let message = "it's alright. have a good time";
1935 let tmpdir = tmpdir();
1936 let filename = &tmpdir.join("file_rt_io_file_test.txt");
1938 let mut write_stream = check!(File::create(filename));
1939 check!(write_stream.write(message.as_bytes()));
1942 let mut read_stream = check!(File::open(filename));
1943 let mut read_buf = [0; 1028];
1944 let read_str = match check!(read_stream.read(&mut read_buf)) {
1945 0 => panic!("shouldn't happen"),
1946 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1948 assert_eq!(read_str, message);
1950 check!(fs::remove_file(filename));
1954 fn invalid_path_raises() {
1955 let tmpdir = tmpdir();
1956 let filename = &tmpdir.join("file_that_does_not_exist.txt");
1957 let result = File::open(filename);
1960 error!(result, "No such file or directory");
1962 error!(result, 2); // ERROR_FILE_NOT_FOUND
1966 fn file_test_iounlinking_invalid_path_should_raise_condition() {
1967 let tmpdir = tmpdir();
1968 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1970 let result = fs::remove_file(filename);
1973 error!(result, "No such file or directory");
1975 error!(result, 2); // ERROR_FILE_NOT_FOUND
1979 fn file_test_io_non_positional_read() {
1980 let message: &str = "ten-four";
1981 let mut read_mem = [0; 8];
1982 let tmpdir = tmpdir();
1983 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1985 let mut rw_stream = check!(File::create(filename));
1986 check!(rw_stream.write(message.as_bytes()));
1989 let mut read_stream = check!(File::open(filename));
1991 let read_buf = &mut read_mem[0..4];
1992 check!(read_stream.read(read_buf));
1995 let read_buf = &mut read_mem[4..8];
1996 check!(read_stream.read(read_buf));
1999 check!(fs::remove_file(filename));
2000 let read_str = str::from_utf8(&read_mem).unwrap();
2001 assert_eq!(read_str, message);
2005 fn file_test_io_seek_and_tell_smoke_test() {
2006 let message = "ten-four";
2007 let mut read_mem = [0; 4];
2008 let set_cursor = 4 as u64;
2009 let tell_pos_pre_read;
2010 let tell_pos_post_read;
2011 let tmpdir = tmpdir();
2012 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
2014 let mut rw_stream = check!(File::create(filename));
2015 check!(rw_stream.write(message.as_bytes()));
2018 let mut read_stream = check!(File::open(filename));
2019 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
2020 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
2021 check!(read_stream.read(&mut read_mem));
2022 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
2024 check!(fs::remove_file(filename));
2025 let read_str = str::from_utf8(&read_mem).unwrap();
2026 assert_eq!(read_str, &message[4..8]);
2027 assert_eq!(tell_pos_pre_read, set_cursor);
2028 assert_eq!(tell_pos_post_read, message.len() as u64);
2032 fn file_test_io_seek_and_write() {
2033 let initial_msg = "food-is-yummy";
2034 let overwrite_msg = "-the-bar!!";
2035 let final_msg = "foo-the-bar!!";
2037 let mut read_mem = [0; 13];
2038 let tmpdir = tmpdir();
2039 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
2041 let mut rw_stream = check!(File::create(filename));
2042 check!(rw_stream.write(initial_msg.as_bytes()));
2043 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
2044 check!(rw_stream.write(overwrite_msg.as_bytes()));
2047 let mut read_stream = check!(File::open(filename));
2048 check!(read_stream.read(&mut read_mem));
2050 check!(fs::remove_file(filename));
2051 let read_str = str::from_utf8(&read_mem).unwrap();
2052 assert!(read_str == final_msg);
2056 fn file_test_io_seek_shakedown() {
2058 let initial_msg = "qwer-asdf-zxcv";
2059 let chunk_one: &str = "qwer";
2060 let chunk_two: &str = "asdf";
2061 let chunk_three: &str = "zxcv";
2062 let mut read_mem = [0; 4];
2063 let tmpdir = tmpdir();
2064 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2066 let mut rw_stream = check!(File::create(filename));
2067 check!(rw_stream.write(initial_msg.as_bytes()));
2070 let mut read_stream = check!(File::open(filename));
2072 check!(read_stream.seek(SeekFrom::End(-4)));
2073 check!(read_stream.read(&mut read_mem));
2074 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2076 check!(read_stream.seek(SeekFrom::Current(-9)));
2077 check!(read_stream.read(&mut read_mem));
2078 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2080 check!(read_stream.seek(SeekFrom::Start(0)));
2081 check!(read_stream.read(&mut read_mem));
2082 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2084 check!(fs::remove_file(filename));
2088 fn file_test_io_eof() {
2089 let tmpdir = tmpdir();
2090 let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2091 let mut buf = [0; 256];
2093 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2094 let mut rw = check!(oo.open(&filename));
2095 assert_eq!(check!(rw.read(&mut buf)), 0);
2096 assert_eq!(check!(rw.read(&mut buf)), 0);
2098 check!(fs::remove_file(&filename));
2103 fn file_test_io_read_write_at() {
2104 use os::unix::fs::FileExt;
2106 let tmpdir = tmpdir();
2107 let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2108 let mut buf = [0; 256];
2109 let write1 = "asdf";
2110 let write2 = "qwer-";
2111 let write3 = "-zxcv";
2112 let content = "qwer-asdf-zxcv";
2114 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2115 let mut rw = check!(oo.open(&filename));
2116 assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2117 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2118 assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2119 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2120 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2121 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2122 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2123 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2124 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2125 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2126 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2127 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2128 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2129 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2130 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2131 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2132 assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2133 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2136 let mut read = check!(File::open(&filename));
2137 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2138 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2139 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2140 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2141 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2142 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2143 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2144 assert_eq!(check!(read.read(&mut buf)), write3.len());
2145 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2146 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2147 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2148 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2149 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2150 assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2151 assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2152 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2154 check!(fs::remove_file(&filename));
2159 fn file_test_io_seek_read_write() {
2160 use os::windows::fs::FileExt;
2162 let tmpdir = tmpdir();
2163 let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2164 let mut buf = [0; 256];
2165 let write1 = "asdf";
2166 let write2 = "qwer-";
2167 let write3 = "-zxcv";
2168 let content = "qwer-asdf-zxcv";
2170 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2171 let mut rw = check!(oo.open(&filename));
2172 assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2173 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2174 assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2175 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2176 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2177 assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2178 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2179 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2180 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2181 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2182 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2183 assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2184 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2185 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2186 assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2187 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2190 let mut read = check!(File::open(&filename));
2191 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2192 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2193 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2194 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2195 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2196 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2197 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2198 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2199 assert_eq!(check!(read.read(&mut buf)), write3.len());
2200 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2201 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2202 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2203 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2204 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2205 assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2206 assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2208 check!(fs::remove_file(&filename));
2212 fn file_test_stat_is_correct_on_is_file() {
2213 let tmpdir = tmpdir();
2214 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2216 let mut opts = OpenOptions::new();
2217 let mut fs = check!(opts.read(true).write(true)
2218 .create(true).open(filename));
2220 fs.write(msg.as_bytes()).unwrap();
2222 let fstat_res = check!(fs.metadata());
2223 assert!(fstat_res.is_file());
2225 let stat_res_fn = check!(fs::metadata(filename));
2226 assert!(stat_res_fn.is_file());
2227 let stat_res_meth = check!(filename.metadata());
2228 assert!(stat_res_meth.is_file());
2229 check!(fs::remove_file(filename));
2233 fn file_test_stat_is_correct_on_is_dir() {
2234 let tmpdir = tmpdir();
2235 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2236 check!(fs::create_dir(filename));
2237 let stat_res_fn = check!(fs::metadata(filename));
2238 assert!(stat_res_fn.is_dir());
2239 let stat_res_meth = check!(filename.metadata());
2240 assert!(stat_res_meth.is_dir());
2241 check!(fs::remove_dir(filename));
2245 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2246 let tmpdir = tmpdir();
2247 let dir = &tmpdir.join("fileinfo_false_on_dir");
2248 check!(fs::create_dir(dir));
2249 assert!(!dir.is_file());
2250 check!(fs::remove_dir(dir));
2254 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2255 let tmpdir = tmpdir();
2256 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2257 check!(check!(File::create(file)).write(b"foo"));
2258 assert!(file.exists());
2259 check!(fs::remove_file(file));
2260 assert!(!file.exists());
2264 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2265 let tmpdir = tmpdir();
2266 let dir = &tmpdir.join("before_and_after_dir");
2267 assert!(!dir.exists());
2268 check!(fs::create_dir(dir));
2269 assert!(dir.exists());
2270 assert!(dir.is_dir());
2271 check!(fs::remove_dir(dir));
2272 assert!(!dir.exists());
2276 fn file_test_directoryinfo_readdir() {
2277 let tmpdir = tmpdir();
2278 let dir = &tmpdir.join("di_readdir");
2279 check!(fs::create_dir(dir));
2282 let f = dir.join(&format!("{}.txt", n));
2283 let mut w = check!(File::create(&f));
2284 let msg_str = format!("{}{}", prefix, n.to_string());
2285 let msg = msg_str.as_bytes();
2286 check!(w.write(msg));
2288 let files = check!(fs::read_dir(dir));
2289 let mut mem = [0; 4];
2291 let f = f.unwrap().path();
2293 let n = f.file_stem().unwrap();
2294 check!(check!(File::open(&f)).read(&mut mem));
2295 let read_str = str::from_utf8(&mem).unwrap();
2296 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2297 assert_eq!(expected, read_str);
2299 check!(fs::remove_file(&f));
2301 check!(fs::remove_dir(dir));
2305 fn file_create_new_already_exists_error() {
2306 let tmpdir = tmpdir();
2307 let file = &tmpdir.join("file_create_new_error_exists");
2308 check!(fs::File::create(file));
2309 let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2310 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2314 fn mkdir_path_already_exists_error() {
2315 let tmpdir = tmpdir();
2316 let dir = &tmpdir.join("mkdir_error_twice");
2317 check!(fs::create_dir(dir));
2318 let e = fs::create_dir(dir).unwrap_err();
2319 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2323 fn recursive_mkdir() {
2324 let tmpdir = tmpdir();
2325 let dir = tmpdir.join("d1/d2");
2326 check!(fs::create_dir_all(&dir));
2327 assert!(dir.is_dir())
2331 fn recursive_mkdir_failure() {
2332 let tmpdir = tmpdir();
2333 let dir = tmpdir.join("d1");
2334 let file = dir.join("f1");
2336 check!(fs::create_dir_all(&dir));
2337 check!(File::create(&file));
2339 let result = fs::create_dir_all(&file);
2341 assert!(result.is_err());
2345 fn concurrent_recursive_mkdir() {
2348 let mut dir = dir.join("a");
2350 dir = dir.join("a");
2352 let mut join = vec!();
2354 let dir = dir.clone();
2355 join.push(thread::spawn(move || {
2356 check!(fs::create_dir_all(&dir));
2360 // No `Display` on result of `join()`
2361 join.drain(..).map(|join| join.join().unwrap()).count();
2366 fn recursive_mkdir_slash() {
2367 check!(fs::create_dir_all(Path::new("/")));
2371 fn recursive_mkdir_dot() {
2372 check!(fs::create_dir_all(Path::new(".")));
2376 fn recursive_mkdir_empty() {
2377 check!(fs::create_dir_all(Path::new("")));
2381 fn recursive_rmdir() {
2382 let tmpdir = tmpdir();
2383 let d1 = tmpdir.join("d1");
2384 let dt = d1.join("t");
2385 let dtt = dt.join("t");
2386 let d2 = tmpdir.join("d2");
2387 let canary = d2.join("do_not_delete");
2388 check!(fs::create_dir_all(&dtt));
2389 check!(fs::create_dir_all(&d2));
2390 check!(check!(File::create(&canary)).write(b"foo"));
2391 check!(symlink_junction(&d2, &dt.join("d2")));
2392 let _ = symlink_file(&canary, &d1.join("canary"));
2393 check!(fs::remove_dir_all(&d1));
2395 assert!(!d1.is_dir());
2396 assert!(canary.exists());
2400 fn recursive_rmdir_of_symlink() {
2401 // test we do not recursively delete a symlink but only dirs.
2402 let tmpdir = tmpdir();
2403 let link = tmpdir.join("d1");
2404 let dir = tmpdir.join("d2");
2405 let canary = dir.join("do_not_delete");
2406 check!(fs::create_dir_all(&dir));
2407 check!(check!(File::create(&canary)).write(b"foo"));
2408 check!(symlink_junction(&dir, &link));
2409 check!(fs::remove_dir_all(&link));
2411 assert!(!link.is_dir());
2412 assert!(canary.exists());
2416 // only Windows makes a distinction between file and directory symlinks.
2418 fn recursive_rmdir_of_file_symlink() {
2419 let tmpdir = tmpdir();
2420 if !got_symlink_permission(&tmpdir) { return };
2422 let f1 = tmpdir.join("f1");
2423 let f2 = tmpdir.join("f2");
2424 check!(check!(File::create(&f1)).write(b"foo"));
2425 check!(symlink_file(&f1, &f2));
2426 match fs::remove_dir_all(&f2) {
2427 Ok(..) => panic!("wanted a failure"),
2433 fn unicode_path_is_dir() {
2434 assert!(Path::new(".").is_dir());
2435 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2437 let tmpdir = tmpdir();
2439 let mut dirpath = tmpdir.path().to_path_buf();
2440 dirpath.push("test-가一ー你好");
2441 check!(fs::create_dir(&dirpath));
2442 assert!(dirpath.is_dir());
2444 let mut filepath = dirpath;
2445 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2446 check!(File::create(&filepath)); // ignore return; touch only
2447 assert!(!filepath.is_dir());
2448 assert!(filepath.exists());
2452 fn unicode_path_exists() {
2453 assert!(Path::new(".").exists());
2454 assert!(!Path::new("test/nonexistent-bogus-path").exists());
2456 let tmpdir = tmpdir();
2457 let unicode = tmpdir.path();
2458 let unicode = unicode.join("test-각丁ー再见");
2459 check!(fs::create_dir(&unicode));
2460 assert!(unicode.exists());
2461 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2465 fn copy_file_does_not_exist() {
2466 let from = Path::new("test/nonexistent-bogus-path");
2467 let to = Path::new("test/other-bogus-path");
2469 match fs::copy(&from, &to) {
2472 assert!(!from.exists());
2473 assert!(!to.exists());
2479 fn copy_src_does_not_exist() {
2480 let tmpdir = tmpdir();
2481 let from = Path::new("test/nonexistent-bogus-path");
2482 let to = tmpdir.join("out.txt");
2483 check!(check!(File::create(&to)).write(b"hello"));
2484 assert!(fs::copy(&from, &to).is_err());
2485 assert!(!from.exists());
2486 let mut v = Vec::new();
2487 check!(check!(File::open(&to)).read_to_end(&mut v));
2488 assert_eq!(v, b"hello");
2493 let tmpdir = tmpdir();
2494 let input = tmpdir.join("in.txt");
2495 let out = tmpdir.join("out.txt");
2497 check!(check!(File::create(&input)).write(b"hello"));
2498 check!(fs::copy(&input, &out));
2499 let mut v = Vec::new();
2500 check!(check!(File::open(&out)).read_to_end(&mut v));
2501 assert_eq!(v, b"hello");
2503 assert_eq!(check!(input.metadata()).permissions(),
2504 check!(out.metadata()).permissions());
2508 fn copy_file_dst_dir() {
2509 let tmpdir = tmpdir();
2510 let out = tmpdir.join("out");
2512 check!(File::create(&out));
2513 match fs::copy(&*out, tmpdir.path()) {
2514 Ok(..) => panic!(), Err(..) => {}
2519 fn copy_file_dst_exists() {
2520 let tmpdir = tmpdir();
2521 let input = tmpdir.join("in");
2522 let output = tmpdir.join("out");
2524 check!(check!(File::create(&input)).write("foo".as_bytes()));
2525 check!(check!(File::create(&output)).write("bar".as_bytes()));
2526 check!(fs::copy(&input, &output));
2528 let mut v = Vec::new();
2529 check!(check!(File::open(&output)).read_to_end(&mut v));
2530 assert_eq!(v, b"foo".to_vec());
2534 fn copy_file_src_dir() {
2535 let tmpdir = tmpdir();
2536 let out = tmpdir.join("out");
2538 match fs::copy(tmpdir.path(), &out) {
2539 Ok(..) => panic!(), Err(..) => {}
2541 assert!(!out.exists());
2545 fn copy_file_preserves_perm_bits() {
2546 let tmpdir = tmpdir();
2547 let input = tmpdir.join("in.txt");
2548 let out = tmpdir.join("out.txt");
2550 let attr = check!(check!(File::create(&input)).metadata());
2551 let mut p = attr.permissions();
2552 p.set_readonly(true);
2553 check!(fs::set_permissions(&input, p));
2554 check!(fs::copy(&input, &out));
2555 assert!(check!(out.metadata()).permissions().readonly());
2556 check!(fs::set_permissions(&input, attr.permissions()));
2557 check!(fs::set_permissions(&out, attr.permissions()));
2562 fn copy_file_preserves_streams() {
2564 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2565 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 6);
2566 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2567 let mut v = Vec::new();
2568 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2569 assert_eq!(v, b"carrot".to_vec());
2573 fn symlinks_work() {
2574 let tmpdir = tmpdir();
2575 if !got_symlink_permission(&tmpdir) { return };
2577 let input = tmpdir.join("in.txt");
2578 let out = tmpdir.join("out.txt");
2580 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2581 check!(symlink_file(&input, &out));
2582 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
2583 assert_eq!(check!(fs::metadata(&out)).len(),
2584 check!(fs::metadata(&input)).len());
2585 let mut v = Vec::new();
2586 check!(check!(File::open(&out)).read_to_end(&mut v));
2587 assert_eq!(v, b"foobar".to_vec());
2591 fn symlink_noexist() {
2592 // Symlinks can point to things that don't exist
2593 let tmpdir = tmpdir();
2594 if !got_symlink_permission(&tmpdir) { return };
2596 // Use a relative path for testing. Symlinks get normalized by Windows,
2597 // so we may not get the same path back for absolute paths
2598 check!(symlink_file(&"foo", &tmpdir.join("bar")));
2599 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(),
2606 // directory symlink
2607 assert_eq!(check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
2610 assert_eq!(check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
2611 r"C:\Users\Default");
2612 // junction with special permissions
2613 assert_eq!(check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
2616 let tmpdir = tmpdir();
2617 let link = tmpdir.join("link");
2618 if !got_symlink_permission(&tmpdir) { return };
2619 check!(symlink_file(&"foo", &link));
2620 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
2624 fn readlink_not_symlink() {
2625 let tmpdir = tmpdir();
2626 match fs::read_link(tmpdir.path()) {
2627 Ok(..) => panic!("wanted a failure"),
2634 let tmpdir = tmpdir();
2635 let input = tmpdir.join("in.txt");
2636 let out = tmpdir.join("out.txt");
2638 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2639 check!(fs::hard_link(&input, &out));
2640 assert_eq!(check!(fs::metadata(&out)).len(),
2641 check!(fs::metadata(&input)).len());
2642 assert_eq!(check!(fs::metadata(&out)).len(),
2643 check!(input.metadata()).len());
2644 let mut v = Vec::new();
2645 check!(check!(File::open(&out)).read_to_end(&mut v));
2646 assert_eq!(v, b"foobar".to_vec());
2648 // can't link to yourself
2649 match fs::hard_link(&input, &input) {
2650 Ok(..) => panic!("wanted a failure"),
2653 // can't link to something that doesn't exist
2654 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
2655 Ok(..) => panic!("wanted a failure"),
2662 let tmpdir = tmpdir();
2663 let file = tmpdir.join("in.txt");
2665 check!(File::create(&file));
2666 let attr = check!(fs::metadata(&file));
2667 assert!(!attr.permissions().readonly());
2668 let mut p = attr.permissions();
2669 p.set_readonly(true);
2670 check!(fs::set_permissions(&file, p.clone()));
2671 let attr = check!(fs::metadata(&file));
2672 assert!(attr.permissions().readonly());
2674 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
2675 Ok(..) => panic!("wanted an error"),
2679 p.set_readonly(false);
2680 check!(fs::set_permissions(&file, p));
2685 let tmpdir = tmpdir();
2686 let path = tmpdir.join("in.txt");
2688 let file = check!(File::create(&path));
2689 let attr = check!(fs::metadata(&path));
2690 assert!(!attr.permissions().readonly());
2691 let mut p = attr.permissions();
2692 p.set_readonly(true);
2693 check!(file.set_permissions(p.clone()));
2694 let attr = check!(fs::metadata(&path));
2695 assert!(attr.permissions().readonly());
2697 p.set_readonly(false);
2698 check!(file.set_permissions(p));
2702 fn sync_doesnt_kill_anything() {
2703 let tmpdir = tmpdir();
2704 let path = tmpdir.join("in.txt");
2706 let mut file = check!(File::create(&path));
2707 check!(file.sync_all());
2708 check!(file.sync_data());
2709 check!(file.write(b"foo"));
2710 check!(file.sync_all());
2711 check!(file.sync_data());
2715 fn truncate_works() {
2716 let tmpdir = tmpdir();
2717 let path = tmpdir.join("in.txt");
2719 let mut file = check!(File::create(&path));
2720 check!(file.write(b"foo"));
2721 check!(file.sync_all());
2723 // Do some simple things with truncation
2724 assert_eq!(check!(file.metadata()).len(), 3);
2725 check!(file.set_len(10));
2726 assert_eq!(check!(file.metadata()).len(), 10);
2727 check!(file.write(b"bar"));
2728 check!(file.sync_all());
2729 assert_eq!(check!(file.metadata()).len(), 10);
2731 let mut v = Vec::new();
2732 check!(check!(File::open(&path)).read_to_end(&mut v));
2733 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
2735 // Truncate to a smaller length, don't seek, and then write something.
2736 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
2737 // past the end of the file).
2738 check!(file.set_len(2));
2739 assert_eq!(check!(file.metadata()).len(), 2);
2740 check!(file.write(b"wut"));
2741 check!(file.sync_all());
2742 assert_eq!(check!(file.metadata()).len(), 9);
2743 let mut v = Vec::new();
2744 check!(check!(File::open(&path)).read_to_end(&mut v));
2745 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
2750 use fs::OpenOptions as OO;
2751 fn c<T: Clone>(t: &T) -> T { t.clone() }
2753 let tmpdir = tmpdir();
2755 let mut r = OO::new(); r.read(true);
2756 let mut w = OO::new(); w.write(true);
2757 let mut rw = OO::new(); rw.read(true).write(true);
2758 let mut a = OO::new(); a.append(true);
2759 let mut ra = OO::new(); ra.read(true).append(true);
2762 let invalid_options = 87; // ERROR_INVALID_PARAMETER
2764 let invalid_options = "Invalid argument";
2766 // Test various combinations of creation modes and access modes.
2769 // creation mode | read | write | read-write | append | read-append |
2770 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
2771 // not set (open existing) | X | X | X | X | X |
2772 // create | | X | X | X | X |
2773 // truncate | | X | X | | |
2774 // create and truncate | | X | X | | |
2775 // create_new | | X | X | X | X |
2777 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
2780 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
2781 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
2782 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
2783 check!(c(&w).create(true).open(&tmpdir.join("a")));
2784 check!(c(&w).open(&tmpdir.join("a")));
2787 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
2788 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
2789 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
2790 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
2791 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
2794 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
2795 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
2796 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
2797 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2798 check!(c(&rw).open(&tmpdir.join("c")));
2801 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
2802 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
2803 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
2804 check!(c(&a).create(true).open(&tmpdir.join("d")));
2805 check!(c(&a).open(&tmpdir.join("d")));
2808 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
2809 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
2810 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
2811 check!(c(&ra).create(true).open(&tmpdir.join("e")));
2812 check!(c(&ra).open(&tmpdir.join("e")));
2814 // Test opening a file without setting an access mode
2815 let mut blank = OO::new();
2816 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
2819 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
2821 // Test write fails for read-only
2822 check!(r.open(&tmpdir.join("h")));
2824 let mut f = check!(r.open(&tmpdir.join("h")));
2825 assert!(f.write("wut".as_bytes()).is_err());
2828 // Test write overwrites
2830 let mut f = check!(c(&w).open(&tmpdir.join("h")));
2831 check!(f.write("baz".as_bytes()));
2834 let mut f = check!(c(&r).open(&tmpdir.join("h")));
2835 let mut b = vec![0; 6];
2836 check!(f.read(&mut b));
2837 assert_eq!(b, "bazbar".as_bytes());
2840 // Test truncate works
2842 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
2843 check!(f.write("foo".as_bytes()));
2845 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2847 // Test append works
2848 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2850 let mut f = check!(c(&a).open(&tmpdir.join("h")));
2851 check!(f.write("bar".as_bytes()));
2853 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
2855 // Test .append(true) equals .write(true).append(true)
2857 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
2858 check!(f.write("baz".as_bytes()));
2860 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
2864 fn _assert_send_sync() {
2865 fn _assert_send_sync<T: Send + Sync>() {}
2866 _assert_send_sync::<OpenOptions>();
2871 let mut bytes = [0; 1024];
2872 StdRng::new().unwrap().fill_bytes(&mut bytes);
2874 let tmpdir = tmpdir();
2876 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
2877 let mut v = Vec::new();
2878 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
2879 assert!(v == &bytes[..]);
2883 fn file_try_clone() {
2884 let tmpdir = tmpdir();
2886 let mut f1 = check!(OpenOptions::new()
2890 .open(&tmpdir.join("test")));
2891 let mut f2 = check!(f1.try_clone());
2893 check!(f1.write_all(b"hello world"));
2894 check!(f1.seek(SeekFrom::Start(2)));
2896 let mut buf = vec![];
2897 check!(f2.read_to_end(&mut buf));
2898 assert_eq!(buf, b"llo world");
2901 check!(f1.write_all(b"!"));
2905 #[cfg(not(windows))]
2906 fn unlink_readonly() {
2907 let tmpdir = tmpdir();
2908 let path = tmpdir.join("file");
2909 check!(File::create(&path));
2910 let mut perm = check!(fs::metadata(&path)).permissions();
2911 perm.set_readonly(true);
2912 check!(fs::set_permissions(&path, perm));
2913 check!(fs::remove_file(&path));
2917 fn mkdir_trailing_slash() {
2918 let tmpdir = tmpdir();
2919 let path = tmpdir.join("file");
2920 check!(fs::create_dir_all(&path.join("a/")));
2924 fn canonicalize_works_simple() {
2925 let tmpdir = tmpdir();
2926 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2927 let file = tmpdir.join("test");
2928 File::create(&file).unwrap();
2929 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2933 fn realpath_works() {
2934 let tmpdir = tmpdir();
2935 if !got_symlink_permission(&tmpdir) { return };
2937 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2938 let file = tmpdir.join("test");
2939 let dir = tmpdir.join("test2");
2940 let link = dir.join("link");
2941 let linkdir = tmpdir.join("test3");
2943 File::create(&file).unwrap();
2944 fs::create_dir(&dir).unwrap();
2945 symlink_file(&file, &link).unwrap();
2946 symlink_dir(&dir, &linkdir).unwrap();
2948 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
2950 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
2951 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2952 assert_eq!(fs::canonicalize(&link).unwrap(), file);
2953 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
2954 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
2958 fn realpath_works_tricky() {
2959 let tmpdir = tmpdir();
2960 if !got_symlink_permission(&tmpdir) { return };
2962 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2963 let a = tmpdir.join("a");
2964 let b = a.join("b");
2965 let c = b.join("c");
2966 let d = a.join("d");
2967 let e = d.join("e");
2968 let f = a.join("f");
2970 fs::create_dir_all(&b).unwrap();
2971 fs::create_dir_all(&d).unwrap();
2972 File::create(&f).unwrap();
2973 if cfg!(not(windows)) {
2974 symlink_dir("../d/e", &c).unwrap();
2975 symlink_file("../f", &e).unwrap();
2978 symlink_dir(r"..\d\e", &c).unwrap();
2979 symlink_file(r"..\f", &e).unwrap();
2982 assert_eq!(fs::canonicalize(&c).unwrap(), f);
2983 assert_eq!(fs::canonicalize(&e).unwrap(), f);
2987 fn dir_entry_methods() {
2988 let tmpdir = tmpdir();
2990 fs::create_dir_all(&tmpdir.join("a")).unwrap();
2991 File::create(&tmpdir.join("b")).unwrap();
2993 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
2994 let fname = file.file_name();
2995 match fname.to_str() {
2997 assert!(file.file_type().unwrap().is_dir());
2998 assert!(file.metadata().unwrap().is_dir());
3001 assert!(file.file_type().unwrap().is_file());
3002 assert!(file.metadata().unwrap().is_file());
3004 f => panic!("unknown file name: {:?}", f),
3010 fn dir_entry_debug() {
3011 let tmpdir = tmpdir();
3012 File::create(&tmpdir.join("b")).unwrap();
3013 let mut read_dir = tmpdir.path().read_dir().unwrap();
3014 let dir_entry = read_dir.next().unwrap().unwrap();
3015 let actual = format!("{:?}", dir_entry);
3016 let expected = format!("DirEntry({:?})", dir_entry.0.path());
3017 assert_eq!(actual, expected);
3021 fn read_dir_not_found() {
3022 let res = fs::read_dir("/path/that/does/not/exist");
3023 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
3027 fn create_dir_all_with_junctions() {
3028 let tmpdir = tmpdir();
3029 let target = tmpdir.join("target");
3031 let junction = tmpdir.join("junction");
3032 let b = junction.join("a/b");
3034 let link = tmpdir.join("link");
3035 let d = link.join("c/d");
3037 fs::create_dir(&target).unwrap();
3039 check!(symlink_junction(&target, &junction));
3040 check!(fs::create_dir_all(&b));
3041 // the junction itself is not a directory, but `is_dir()` on a Path
3043 assert!(junction.is_dir());
3044 assert!(b.exists());
3046 if !got_symlink_permission(&tmpdir) { return };
3047 check!(symlink_dir(&target, &link));
3048 check!(fs::create_dir_all(&d));
3049 assert!(link.is_dir());
3050 assert!(d.exists());
3054 fn metadata_access_times() {
3055 let tmpdir = tmpdir();
3057 let b = tmpdir.join("b");
3058 File::create(&b).unwrap();
3060 let a = check!(fs::metadata(&tmpdir.path()));
3061 let b = check!(fs::metadata(&b));
3063 assert_eq!(check!(a.accessed()), check!(a.accessed()));
3064 assert_eq!(check!(a.modified()), check!(a.modified()));
3065 assert_eq!(check!(b.accessed()), check!(b.modified()));
3067 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3068 check!(a.created());
3069 check!(b.created());