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, Write};
23 use path::{Path, PathBuf};
24 use sys::fs as fs_imp;
25 use sys_common::io::read_to_end_uninitialized;
26 use sys_common::{AsInnerMut, FromInner, AsInner, IntoInner};
29 /// A reference to an open file on the filesystem.
31 /// An instance of a `File` can be read and/or written depending on what options
32 /// it was opened with. Files also implement `Seek` to alter the logical cursor
33 /// that the file contains internally.
38 /// use std::io::prelude::*;
39 /// use std::fs::File;
41 /// # fn foo() -> std::io::Result<()> {
42 /// let mut f = try!(File::create("foo.txt"));
43 /// try!(f.write_all(b"Hello, world!"));
45 /// let mut f = try!(File::open("foo.txt"));
46 /// let mut s = String::new();
47 /// try!(f.read_to_string(&mut s));
48 /// assert_eq!(s, "Hello, world!");
52 #[stable(feature = "rust1", since = "1.0.0")]
57 /// Metadata information about a file.
59 /// This structure is returned from the `metadata` function or method and
60 /// represents known metadata about a file such as its permissions, size,
61 /// modification times, etc.
62 #[stable(feature = "rust1", since = "1.0.0")]
64 pub struct Metadata(fs_imp::FileAttr);
66 /// Iterator over the entries in a directory.
68 /// This iterator is returned from the `read_dir` function of this module and
69 /// will yield instances of `io::Result<DirEntry>`. Through a `DirEntry`
70 /// information like the entry's path and possibly other metadata can be
75 /// This `io::Result` will be an `Err` if there's some sort of intermittent
76 /// IO error during iteration.
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub struct ReadDir(fs_imp::ReadDir);
80 /// Entries returned by the `ReadDir` iterator.
82 /// An instance of `DirEntry` represents an entry inside of a directory on the
83 /// filesystem. Each entry can be inspected via methods to learn about the full
84 /// path or possibly other metadata through per-platform extension traits.
85 #[stable(feature = "rust1", since = "1.0.0")]
86 pub struct DirEntry(fs_imp::DirEntry);
88 /// An iterator that recursively walks over the contents of a directory.
89 #[unstable(feature = "fs_walk",
90 reason = "the precise semantics and defaults for a recursive walk \
91 may change and this may end up accounting for files such \
92 as symlinks differently",
94 #[rustc_deprecated(reason = "superceded by the walkdir crate",
98 stack: Vec<io::Result<ReadDir>>,
101 /// Options and flags which can be used to configure how a file is opened.
103 /// This builder exposes the ability to configure how a `File` is opened and
104 /// what operations are permitted on the open file. The `File::open` and
105 /// `File::create` methods are aliases for commonly used options using this
108 /// Generally speaking, when using `OpenOptions`, you'll first call `new()`,
109 /// then chain calls to methods to set each option, then call `open()`, passing
110 /// the path of the file you're trying to open. This will give you a
111 /// [`io::Result`][result] with a [`File`][file] inside that you can further
114 /// [result]: ../io/type.Result.html
115 /// [file]: struct.File.html
119 /// Opening a file to read:
122 /// use std::fs::OpenOptions;
124 /// let file = OpenOptions::new().read(true).open("foo.txt");
127 /// Opening a file for both reading and writing, as well as creating it if it
131 /// use std::fs::OpenOptions;
133 /// let file = OpenOptions::new()
137 /// .open("foo.txt");
140 #[stable(feature = "rust1", since = "1.0.0")]
141 pub struct OpenOptions(fs_imp::OpenOptions);
143 /// Representation of the various permissions on a file.
145 /// This module only currently provides one bit of information, `readonly`,
146 /// which is exposed on all currently supported platforms. Unix-specific
147 /// functionality, such as mode bits, is available through the
148 /// `os::unix::PermissionsExt` trait.
149 #[derive(Clone, PartialEq, Eq, Debug)]
150 #[stable(feature = "rust1", since = "1.0.0")]
151 pub struct Permissions(fs_imp::FilePermissions);
153 /// An structure representing a type of file with accessors for each file type.
154 #[stable(feature = "file_type", since = "1.1.0")]
155 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
156 pub struct FileType(fs_imp::FileType);
158 /// A builder used to create directories in various manners.
160 /// This builder also supports platform-specific options.
161 #[stable(feature = "dir_builder", since = "1.6.0")]
162 pub struct DirBuilder {
163 inner: fs_imp::DirBuilder,
168 /// Attempts to open a file in read-only mode.
170 /// See the `OpenOptions::open` method for more details.
174 /// This function will return an error if `path` does not already exist.
175 /// Other errors may also be returned according to `OpenOptions::open`.
180 /// use std::fs::File;
182 /// # fn foo() -> std::io::Result<()> {
183 /// let mut f = try!(File::open("foo.txt"));
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
189 OpenOptions::new().read(true).open(path.as_ref())
192 /// Opens a file in write-only mode.
194 /// This function will create a file if it does not exist,
195 /// and will truncate it if it does.
197 /// See the `OpenOptions::open` function for more details.
202 /// use std::fs::File;
204 /// # fn foo() -> std::io::Result<()> {
205 /// let mut f = try!(File::create("foo.txt"));
209 #[stable(feature = "rust1", since = "1.0.0")]
210 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
211 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
214 /// Attempts to sync all OS-internal metadata to disk.
216 /// This function will attempt to ensure that all in-core data reaches the
217 /// filesystem before returning.
222 /// use std::fs::File;
223 /// use std::io::prelude::*;
225 /// # fn foo() -> std::io::Result<()> {
226 /// let mut f = try!(File::create("foo.txt"));
227 /// try!(f.write_all(b"Hello, world!"));
229 /// try!(f.sync_all());
233 #[stable(feature = "rust1", since = "1.0.0")]
234 pub fn sync_all(&self) -> io::Result<()> {
238 /// This function is similar to `sync_all`, except that it may not
239 /// synchronize file metadata to the filesystem.
241 /// This is intended for use cases that must synchronize content, but don't
242 /// need the metadata on disk. The goal of this method is to reduce disk
245 /// Note that some platforms may simply implement this in terms of
251 /// use std::fs::File;
252 /// use std::io::prelude::*;
254 /// # fn foo() -> std::io::Result<()> {
255 /// let mut f = try!(File::create("foo.txt"));
256 /// try!(f.write_all(b"Hello, world!"));
258 /// try!(f.sync_data());
262 #[stable(feature = "rust1", since = "1.0.0")]
263 pub fn sync_data(&self) -> io::Result<()> {
264 self.inner.datasync()
267 /// Truncates or extends the underlying file, updating the size of
268 /// this file to become `size`.
270 /// If the `size` is less than the current file's size, then the file will
271 /// be shrunk. If it is greater than the current file's size, then the file
272 /// will be extended to `size` and have all of the intermediate data filled
277 /// This function will return an error if the file is not opened for writing.
282 /// use std::fs::File;
284 /// # fn foo() -> std::io::Result<()> {
285 /// let mut f = try!(File::create("foo.txt"));
286 /// try!(f.set_len(10));
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub fn set_len(&self, size: u64) -> io::Result<()> {
292 self.inner.truncate(size)
295 /// Queries metadata about the underlying file.
300 /// use std::fs::File;
302 /// # fn foo() -> std::io::Result<()> {
303 /// let mut f = try!(File::open("foo.txt"));
304 /// let metadata = try!(f.metadata());
308 #[stable(feature = "rust1", since = "1.0.0")]
309 pub fn metadata(&self) -> io::Result<Metadata> {
310 self.inner.file_attr().map(Metadata)
314 impl AsInner<fs_imp::File> for File {
315 fn as_inner(&self) -> &fs_imp::File { &self.inner }
317 impl FromInner<fs_imp::File> for File {
318 fn from_inner(f: fs_imp::File) -> File {
322 impl IntoInner<fs_imp::File> for File {
323 fn into_inner(self) -> fs_imp::File {
328 #[stable(feature = "rust1", since = "1.0.0")]
329 impl fmt::Debug for File {
330 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
335 #[stable(feature = "rust1", since = "1.0.0")]
337 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
340 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
341 unsafe { read_to_end_uninitialized(self, buf) }
344 #[stable(feature = "rust1", since = "1.0.0")]
345 impl Write for File {
346 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
347 self.inner.write(buf)
349 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
351 #[stable(feature = "rust1", since = "1.0.0")]
353 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
357 #[stable(feature = "rust1", since = "1.0.0")]
358 impl<'a> Read for &'a File {
359 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
363 #[stable(feature = "rust1", since = "1.0.0")]
364 impl<'a> Write for &'a File {
365 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
366 self.inner.write(buf)
368 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
370 #[stable(feature = "rust1", since = "1.0.0")]
371 impl<'a> Seek for &'a File {
372 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
378 /// Creates a blank new set of options ready for configuration.
380 /// All options are initially set to `false`.
385 /// use std::fs::OpenOptions;
387 /// let mut options = OpenOptions::new();
388 /// let file = options.read(true).open("foo.txt");
390 #[stable(feature = "rust1", since = "1.0.0")]
391 pub fn new() -> OpenOptions {
392 OpenOptions(fs_imp::OpenOptions::new())
395 /// Sets the option for read access.
397 /// This option, when true, will indicate that the file should be
398 /// `read`-able if opened.
403 /// use std::fs::OpenOptions;
405 /// let file = OpenOptions::new().read(true).open("foo.txt");
407 #[stable(feature = "rust1", since = "1.0.0")]
408 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
409 self.0.read(read); self
412 /// Sets the option for write access.
414 /// This option, when true, will indicate that the file should be
415 /// `write`-able if opened.
417 /// If a file already exist, the contents of that file get overwritten, but it is
423 /// use std::fs::OpenOptions;
425 /// let file = OpenOptions::new().write(true).open("foo.txt");
427 #[stable(feature = "rust1", since = "1.0.0")]
428 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
429 self.0.write(write); self
432 /// Sets the option for the append mode.
434 /// This option, when true, means that writes will append to a file instead
435 /// of overwriting previous contents.
436 /// Note that setting `.write(true).append(true)` has the same effect as
437 /// setting only `.append(true)`.
439 /// For most filesystems the operating system guarantees all writes are atomic:
440 /// no writes get mangled because another process writes at the same time.
442 /// One maybe obvious note when using append-mode: make sure that all data that
443 /// belongs together, is written the the file in one operation. This can be done
444 /// by concatenating strings before passing them to `write()`, or using a buffered
445 /// writer (with a more than adequately sized buffer) and calling `flush()` when the
446 /// message is complete.
448 /// If a file is opened with both read and append access, beware that after opening
449 /// and after every write the position for reading may be set at the end of the file.
450 /// So before writing save the current position (using `seek(SeekFrom::Current(0))`,
451 /// and restore it before the next read.
456 /// use std::fs::OpenOptions;
458 /// let file = OpenOptions::new().append(true).open("foo.txt");
460 #[stable(feature = "rust1", since = "1.0.0")]
461 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
462 self.0.append(append); self
465 /// Sets the option for truncating a previous file.
467 /// If a file is successfully opened with this option set it will truncate
468 /// the file to 0 length if it already exists.
470 /// The file must be opened with write access for truncate to work.
475 /// use std::fs::OpenOptions;
477 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
479 #[stable(feature = "rust1", since = "1.0.0")]
480 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
481 self.0.truncate(truncate); self
484 /// Sets the option for creating a new file.
486 /// This option indicates whether a new file will be created if the file
487 /// does not yet already exist.
489 /// The file must be opened with write or append access in order to create
495 /// use std::fs::OpenOptions;
497 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
499 #[stable(feature = "rust1", since = "1.0.0")]
500 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
501 self.0.create(create); self
504 /// Sets the option to always create a new file.
506 /// This option indicates whether a new file will be created.
507 /// No file is allowed to exist at the target location, also no (dangling)
510 /// if `.create_new(true)` is set, `.create()` and `.truncate()` are ignored.
512 /// The file must be opened with write or append access in order to create
518 /// #![feature(expand_open_options)]
519 /// use std::fs::OpenOptions;
521 /// let file = OpenOptions::new().write(true).create_new(true).open("foo.txt");
523 #[unstable(feature = "expand_open_options",
524 reason = "recently added",
526 pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
527 self.0.create_new(create_new); self
530 /// Opens a file at `path` with the options specified by `self`.
534 /// This function will return an error under a number of different
535 /// circumstances, to include but not limited to:
537 /// * Opening a file that does not exist without setting `create` or `create_new`.
538 /// * Attempting to open a file with access that the user lacks
540 /// * Filesystem-level errors (full disk, etc)
541 /// * Invalid combinations of open options (truncate without write access,
542 /// no access mode set, etc)
547 /// use std::fs::OpenOptions;
549 /// let file = OpenOptions::new().open("foo.txt");
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
553 self._open(path.as_ref())
556 fn _open(&self, path: &Path) -> io::Result<File> {
557 let inner = try!(fs_imp::File::open(path, &self.0));
558 Ok(File { inner: inner })
562 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
563 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
567 /// Returns the file type for this metadata.
568 #[stable(feature = "file_type", since = "1.1.0")]
569 pub fn file_type(&self) -> FileType {
570 FileType(self.0.file_type())
573 /// Returns whether this metadata is for a directory.
578 /// # fn foo() -> std::io::Result<()> {
581 /// let metadata = try!(fs::metadata("foo.txt"));
583 /// assert!(!metadata.is_dir());
587 #[stable(feature = "rust1", since = "1.0.0")]
588 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
590 /// Returns whether this metadata is for a regular file.
595 /// # fn foo() -> std::io::Result<()> {
598 /// let metadata = try!(fs::metadata("foo.txt"));
600 /// assert!(metadata.is_file());
604 #[stable(feature = "rust1", since = "1.0.0")]
605 pub fn is_file(&self) -> bool { self.file_type().is_file() }
607 /// Returns the size of the file, in bytes, this metadata is for.
612 /// # fn foo() -> std::io::Result<()> {
615 /// let metadata = try!(fs::metadata("foo.txt"));
617 /// assert_eq!(0, metadata.len());
621 #[stable(feature = "rust1", since = "1.0.0")]
622 pub fn len(&self) -> u64 { self.0.size() }
624 /// Returns the permissions of the file this metadata is for.
629 /// # fn foo() -> std::io::Result<()> {
632 /// let metadata = try!(fs::metadata("foo.txt"));
634 /// assert!(!metadata.permissions().readonly());
638 #[stable(feature = "rust1", since = "1.0.0")]
639 pub fn permissions(&self) -> Permissions {
640 Permissions(self.0.perm())
644 impl AsInner<fs_imp::FileAttr> for Metadata {
645 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
649 /// Returns whether these permissions describe a readonly file.
654 /// use std::fs::File;
656 /// # fn foo() -> std::io::Result<()> {
657 /// let mut f = try!(File::create("foo.txt"));
658 /// let metadata = try!(f.metadata());
660 /// assert_eq!(false, metadata.permissions().readonly());
664 #[stable(feature = "rust1", since = "1.0.0")]
665 pub fn readonly(&self) -> bool { self.0.readonly() }
667 /// Modifies the readonly flag for this set of permissions.
669 /// This operation does **not** modify the filesystem. To modify the
670 /// filesystem use the `fs::set_permissions` function.
675 /// use std::fs::File;
677 /// # fn foo() -> std::io::Result<()> {
678 /// let f = try!(File::create("foo.txt"));
679 /// let metadata = try!(f.metadata());
680 /// let mut permissions = metadata.permissions();
682 /// permissions.set_readonly(true);
684 /// // filesystem doesn't change
685 /// assert_eq!(false, metadata.permissions().readonly());
687 /// // just this particular `permissions`.
688 /// assert_eq!(true, permissions.readonly());
692 #[stable(feature = "rust1", since = "1.0.0")]
693 pub fn set_readonly(&mut self, readonly: bool) {
694 self.0.set_readonly(readonly)
699 /// Test whether this file type represents a directory.
700 #[stable(feature = "file_type", since = "1.1.0")]
701 pub fn is_dir(&self) -> bool { self.0.is_dir() }
703 /// Test whether this file type represents a regular file.
704 #[stable(feature = "file_type", since = "1.1.0")]
705 pub fn is_file(&self) -> bool { self.0.is_file() }
707 /// Test whether this file type represents a symbolic link.
708 #[stable(feature = "file_type", since = "1.1.0")]
709 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
712 impl AsInner<fs_imp::FileType> for FileType {
713 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
716 impl FromInner<fs_imp::FilePermissions> for Permissions {
717 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
722 impl AsInner<fs_imp::FilePermissions> for Permissions {
723 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
726 #[stable(feature = "rust1", since = "1.0.0")]
727 impl Iterator for ReadDir {
728 type Item = io::Result<DirEntry>;
730 fn next(&mut self) -> Option<io::Result<DirEntry>> {
731 self.0.next().map(|entry| entry.map(DirEntry))
736 /// Returns the full path to the file that this entry represents.
738 /// The full path is created by joining the original path to `read_dir` or
739 /// `walk_dir` with the filename of this entry.
745 /// # fn foo() -> std::io::Result<()> {
746 /// for entry in try!(fs::read_dir(".")) {
747 /// let dir = try!(entry);
748 /// println!("{:?}", dir.path());
754 /// This prints output like:
759 /// "./hello_world.rs"
762 /// The exact text, of course, depends on what files you have in `.`.
763 #[stable(feature = "rust1", since = "1.0.0")]
764 pub fn path(&self) -> PathBuf { self.0.path() }
766 /// Return the metadata for the file that this entry points at.
768 /// This function will not traverse symlinks if this entry points at a
771 /// # Platform-specific behavior
773 /// On Windows this function is cheap to call (no extra system calls
774 /// needed), but on Unix platforms this function is the equivalent of
775 /// calling `symlink_metadata` on the path.
776 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
777 pub fn metadata(&self) -> io::Result<Metadata> {
778 self.0.metadata().map(Metadata)
781 /// Return the file type for the file that this entry points at.
783 /// This function will not traverse symlinks if this entry points at a
786 /// # Platform-specific behavior
788 /// On Windows and most Unix platforms this function is free (no extra
789 /// system calls needed), but some Unix platforms may require the equivalent
790 /// call to `symlink_metadata` to learn about the target file type.
791 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
792 pub fn file_type(&self) -> io::Result<FileType> {
793 self.0.file_type().map(FileType)
796 /// Returns the bare file name of this directory entry without any other
797 /// leading path component.
798 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
799 pub fn file_name(&self) -> OsString {
804 impl AsInner<fs_imp::DirEntry> for DirEntry {
805 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
808 /// Removes a file from the filesystem.
810 /// Note that there is no
811 /// guarantee that the file is immediately deleted (e.g. depending on
812 /// platform, other open file descriptors may prevent immediate removal).
814 /// # Platform-specific behavior
816 /// This function currently corresponds to the `unlink` function on Unix
817 /// and the `DeleteFile` function on Windows.
818 /// Note that, this [may change in the future][changes].
819 /// [changes]: ../io/index.html#platform-specific-behavior
823 /// This function will return an error in the following situations, but is not
824 /// limited to just these cases:
826 /// * `path` points to a directory.
827 /// * The user lacks permissions to remove the file.
834 /// # fn foo() -> std::io::Result<()> {
835 /// try!(fs::remove_file("a.txt"));
839 #[stable(feature = "rust1", since = "1.0.0")]
840 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
841 fs_imp::unlink(path.as_ref())
844 /// Given a path, query the file system to get information about a file,
847 /// This function will traverse symbolic links to query information about the
848 /// destination file.
850 /// # Platform-specific behavior
852 /// This function currently corresponds to the `stat` function on Unix
853 /// and the `GetFileAttributesEx` function on Windows.
854 /// Note that, this [may change in the future][changes].
855 /// [changes]: ../io/index.html#platform-specific-behavior
859 /// This function will return an error in the following situations, but is not
860 /// limited to just these cases:
862 /// * The user lacks permissions to perform `metadata` call on `path`.
863 /// * `path` does not exist.
868 /// # fn foo() -> std::io::Result<()> {
871 /// let attr = try!(fs::metadata("/some/file/path.txt"));
872 /// // inspect attr ...
876 #[stable(feature = "rust1", since = "1.0.0")]
877 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
878 fs_imp::stat(path.as_ref()).map(Metadata)
881 /// Query the metadata about a file without following symlinks.
883 /// # Platform-specific behavior
885 /// This function currently corresponds to the `lstat` function on Unix
886 /// and the `GetFileAttributesEx` function on Windows.
887 /// Note that, this [may change in the future][changes].
888 /// [changes]: ../io/index.html#platform-specific-behavior
892 /// This function will return an error in the following situations, but is not
893 /// limited to just these cases:
895 /// * The user lacks permissions to perform `metadata` call on `path`.
896 /// * `path` does not exist.
901 /// # fn foo() -> std::io::Result<()> {
904 /// let attr = try!(fs::symlink_metadata("/some/file/path.txt"));
905 /// // inspect attr ...
909 #[stable(feature = "symlink_metadata", since = "1.1.0")]
910 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
911 fs_imp::lstat(path.as_ref()).map(Metadata)
914 /// Rename a file or directory to a new name.
916 /// This will not work if the new name is on a different mount point.
918 /// # Platform-specific behavior
920 /// This function currently corresponds to the `rename` function on Unix
921 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
922 /// Note that, this [may change in the future][changes].
923 /// [changes]: ../io/index.html#platform-specific-behavior
927 /// This function will return an error in the following situations, but is not
928 /// limited to just these cases:
930 /// * `from` does not exist.
931 /// * The user lacks permissions to view contents.
932 /// * `from` and `to` are on separate filesystems.
939 /// # fn foo() -> std::io::Result<()> {
940 /// try!(fs::rename("a.txt", "b.txt")); // Rename a.txt to b.txt
944 #[stable(feature = "rust1", since = "1.0.0")]
945 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
946 fs_imp::rename(from.as_ref(), to.as_ref())
949 /// Copies the contents of one file to another. This function will also
950 /// copy the permission bits of the original file to the destination file.
952 /// This function will **overwrite** the contents of `to`.
954 /// Note that if `from` and `to` both point to the same file, then the file
955 /// will likely get truncated by this operation.
957 /// On success, the total number of bytes copied is returned.
959 /// # Platform-specific behavior
961 /// This function currently corresponds to the `open` function in Unix
962 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
963 /// `O_CLOEXEC` is set for returned file descriptors.
964 /// On Windows, this function currently corresponds to `CopyFileEx`.
965 /// Note that, this [may change in the future][changes].
966 /// [changes]: ../io/index.html#platform-specific-behavior
970 /// This function will return an error in the following situations, but is not
971 /// limited to just these cases:
973 /// * The `from` path is not a file.
974 /// * The `from` file does not exist.
975 /// * The current process does not have the permission rights to access
976 /// `from` or write `to`.
983 /// # fn foo() -> std::io::Result<()> {
984 /// try!(fs::copy("foo.txt", "bar.txt")); // Copy foo.txt to bar.txt
987 #[stable(feature = "rust1", since = "1.0.0")]
988 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
989 fs_imp::copy(from.as_ref(), to.as_ref())
992 /// Creates a new hard link on the filesystem.
994 /// The `dst` path will be a link pointing to the `src` path. Note that systems
995 /// often require these two paths to both be located on the same filesystem.
997 /// # Platform-specific behavior
999 /// This function currently corresponds to the `link` function on Unix
1000 /// and the `CreateHardLink` function on Windows.
1001 /// Note that, this [may change in the future][changes].
1002 /// [changes]: ../io/index.html#platform-specific-behavior
1006 /// This function will return an error in the following situations, but is not
1007 /// limited to just these cases:
1009 /// * The `src` path is not a file or doesn't exist.
1016 /// # fn foo() -> std::io::Result<()> {
1017 /// try!(fs::hard_link("a.txt", "b.txt")); // Hard link a.txt to b.txt
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1023 fs_imp::link(src.as_ref(), dst.as_ref())
1026 /// Creates a new symbolic link on the filesystem.
1028 /// The `dst` path will be a symbolic link pointing to the `src` path.
1029 /// On Windows, this will be a file symlink, not a directory symlink;
1030 /// for this reason, the platform-specific `std::os::unix::fs::symlink`
1031 /// and `std::os::windows::fs::{symlink_file, symlink_dir}` should be
1032 /// used instead to make the intent explicit.
1039 /// # fn foo() -> std::io::Result<()> {
1040 /// try!(fs::soft_link("a.txt", "b.txt"));
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 #[rustc_deprecated(since = "1.1.0",
1046 reason = "replaced with std::os::unix::fs::symlink and \
1047 std::os::windows::fs::{symlink_file, symlink_dir}")]
1048 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1049 fs_imp::symlink(src.as_ref(), dst.as_ref())
1052 /// Reads a symbolic link, returning the file that the link points to.
1054 /// # Platform-specific behavior
1056 /// This function currently corresponds to the `readlink` function on Unix
1057 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1058 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1059 /// Note that, this [may change in the future][changes].
1060 /// [changes]: ../io/index.html#platform-specific-behavior
1064 /// This function will return an error in the following situations, but is not
1065 /// limited to just these cases:
1067 /// * `path` is not a symbolic link.
1068 /// * `path` does not exist.
1075 /// # fn foo() -> std::io::Result<()> {
1076 /// let path = try!(fs::read_link("a.txt"));
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1082 fs_imp::readlink(path.as_ref())
1085 /// Returns the canonical form of a path with all intermediate components
1086 /// normalized and symbolic links resolved.
1088 /// # Platform-specific behavior
1090 /// This function currently corresponds to the `realpath` function on Unix
1091 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1092 /// Note that, this [may change in the future][changes].
1093 /// [changes]: ../io/index.html#platform-specific-behavior
1097 /// This function will return an error in the following situations, but is not
1098 /// limited to just these cases:
1100 /// * `path` does not exist.
1101 /// * A component in path is not a directory.
1108 /// # fn foo() -> std::io::Result<()> {
1109 /// let path = try!(fs::canonicalize("../a/../foo.txt"));
1113 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1114 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1115 fs_imp::canonicalize(path.as_ref())
1118 /// Creates a new, empty directory at the provided path
1120 /// # Platform-specific behavior
1122 /// This function currently corresponds to the `mkdir` function on Unix
1123 /// and the `CreateDirectory` function on Windows.
1124 /// Note that, this [may change in the future][changes].
1125 /// [changes]: ../io/index.html#platform-specific-behavior
1129 /// This function will return an error in the following situations, but is not
1130 /// limited to just these cases:
1132 /// * User lacks permissions to create directory at `path`.
1133 /// * `path` already exists.
1140 /// # fn foo() -> std::io::Result<()> {
1141 /// try!(fs::create_dir("/some/dir"));
1145 #[stable(feature = "rust1", since = "1.0.0")]
1146 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1147 DirBuilder::new().create(path.as_ref())
1150 /// Recursively create a directory and all of its parent components if they
1153 /// # Platform-specific behavior
1155 /// This function currently corresponds to the `mkdir` function on Unix
1156 /// and the `CreateDirectory` function on Windows.
1157 /// Note that, this [may change in the future][changes].
1158 /// [changes]: ../io/index.html#platform-specific-behavior
1162 /// This function will return an error in the following situations, but is not
1163 /// limited to just these cases:
1165 /// * If any directory in the path specified by `path`
1166 /// does not already exist and it could not be created otherwise. The specific
1167 /// error conditions for when a directory is being created (after it is
1168 /// determined to not exist) are outlined by `fs::create_dir`.
1175 /// # fn foo() -> std::io::Result<()> {
1176 /// try!(fs::create_dir_all("/some/dir"));
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1182 DirBuilder::new().recursive(true).create(path.as_ref())
1185 /// Removes an existing, empty directory.
1187 /// # Platform-specific behavior
1189 /// This function currently corresponds to the `rmdir` function on Unix
1190 /// and the `RemoveDirectory` function on Windows.
1191 /// Note that, this [may change in the future][changes].
1192 /// [changes]: ../io/index.html#platform-specific-behavior
1196 /// This function will return an error in the following situations, but is not
1197 /// limited to just these cases:
1199 /// * The user lacks permissions to remove the directory at the provided `path`.
1200 /// * The directory isn't empty.
1207 /// # fn foo() -> std::io::Result<()> {
1208 /// try!(fs::remove_dir("/some/dir"));
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1214 fs_imp::rmdir(path.as_ref())
1217 /// Removes a directory at this path, after removing all its contents. Use
1220 /// This function does **not** follow symbolic links and it will simply remove the
1221 /// symbolic link itself.
1223 /// # Platform-specific behavior
1225 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1226 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1228 /// Note that, this [may change in the future][changes].
1229 /// [changes]: ../io/index.html#platform-specific-behavior
1233 /// See `file::remove_file` and `fs::remove_dir`.
1240 /// # fn foo() -> std::io::Result<()> {
1241 /// try!(fs::remove_dir_all("/some/dir"));
1245 #[stable(feature = "rust1", since = "1.0.0")]
1246 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1247 _remove_dir_all(path.as_ref())
1250 fn _remove_dir_all(path: &Path) -> io::Result<()> {
1251 for child in try!(read_dir(path)) {
1252 let child = try!(child).path();
1253 let stat = try!(symlink_metadata(&*child));
1255 try!(remove_dir_all(&*child));
1257 try!(remove_file(&*child));
1263 /// Returns an iterator over the entries within a directory.
1265 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1266 /// be encountered after an iterator is initially constructed.
1268 /// # Platform-specific behavior
1270 /// This function currently corresponds to the `opendir` function on Unix
1271 /// and the `FindFirstFile` function on Windows.
1272 /// Note that, this [may change in the future][changes].
1273 /// [changes]: ../io/index.html#platform-specific-behavior
1277 /// This function will return an error in the following situations, but is not
1278 /// limited to just these cases:
1280 /// * The provided `path` doesn't exist.
1281 /// * The process lacks permissions to view the contents.
1282 /// * The `path` points at a non-directory file.
1288 /// use std::fs::{self, DirEntry};
1289 /// use std::path::Path;
1291 /// // one possible implementation of fs::walk_dir only visiting files
1292 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1293 /// if try!(fs::metadata(dir)).is_dir() {
1294 /// for entry in try!(fs::read_dir(dir)) {
1295 /// let entry = try!(entry);
1296 /// if try!(fs::metadata(entry.path())).is_dir() {
1297 /// try!(visit_dirs(&entry.path(), cb));
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1308 fs_imp::readdir(path.as_ref()).map(ReadDir)
1311 /// Returns an iterator that will recursively walk the directory structure
1312 /// rooted at `path`.
1314 /// The path given will not be iterated over, and this will perform iteration in
1315 /// some top-down order. The contents of unreadable subdirectories are ignored.
1317 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1318 /// be encountered after an iterator is initially constructed.
1319 #[unstable(feature = "fs_walk",
1320 reason = "the precise semantics and defaults for a recursive walk \
1321 may change and this may end up accounting for files such \
1322 as symlinks differently",
1324 #[rustc_deprecated(reason = "superceded by the walkdir crate",
1326 #[allow(deprecated)]
1327 pub fn walk_dir<P: AsRef<Path>>(path: P) -> io::Result<WalkDir> {
1328 _walk_dir(path.as_ref())
1331 #[allow(deprecated)]
1332 fn _walk_dir(path: &Path) -> io::Result<WalkDir> {
1333 let start = try!(read_dir(path));
1334 Ok(WalkDir { cur: Some(start), stack: Vec::new() })
1337 #[unstable(feature = "fs_walk", issue = "27707")]
1338 #[rustc_deprecated(reason = "superceded by the walkdir crate",
1340 #[allow(deprecated)]
1341 impl Iterator for WalkDir {
1342 type Item = io::Result<DirEntry>;
1344 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1346 if let Some(ref mut cur) = self.cur {
1348 Some(Err(e)) => return Some(Err(e)),
1350 let path = next.path();
1352 self.stack.push(read_dir(&*path));
1354 return Some(Ok(next))
1360 match self.stack.pop() {
1361 Some(Err(e)) => return Some(Err(e)),
1362 Some(Ok(next)) => self.cur = Some(next),
1363 None => return None,
1369 /// Changes the permissions found on a file or a directory.
1371 /// # Platform-specific behavior
1373 /// This function currently corresponds to the `chmod` function on Unix
1374 /// and the `SetFileAttributes` function on Windows.
1375 /// Note that, this [may change in the future][changes].
1376 /// [changes]: ../io/index.html#platform-specific-behavior
1380 /// This function will return an error in the following situations, but is not
1381 /// limited to just these cases:
1383 /// * `path` does not exist.
1384 /// * The user lacks the permission to change attributes of the file.
1389 /// # fn foo() -> std::io::Result<()> {
1392 /// let mut perms = try!(fs::metadata("foo.txt")).permissions();
1393 /// perms.set_readonly(true);
1394 /// try!(fs::set_permissions("foo.txt", perms));
1398 #[stable(feature = "set_permissions", since = "1.1.0")]
1399 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1401 fs_imp::set_perm(path.as_ref(), perm.0)
1405 /// Creates a new set of options with default mode/security settings for all
1406 /// platforms and also non-recursive.
1407 #[stable(feature = "dir_builder", since = "1.6.0")]
1408 pub fn new() -> DirBuilder {
1410 inner: fs_imp::DirBuilder::new(),
1415 /// Indicate that directories create should be created recursively, creating
1416 /// all parent directories if they do not exist with the same security and
1417 /// permissions settings.
1419 /// This option defaults to `false`
1420 #[stable(feature = "dir_builder", since = "1.6.0")]
1421 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1422 self.recursive = recursive;
1426 /// Create the specified directory with the options configured in this
1432 /// use std::fs::{self, DirBuilder};
1434 /// let path = "/tmp/foo/bar/baz";
1435 /// DirBuilder::new()
1436 /// .recursive(true)
1437 /// .create(path).unwrap();
1439 /// assert!(fs::metadata(path).unwrap().is_dir());
1441 #[stable(feature = "dir_builder", since = "1.6.0")]
1442 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1443 self._create(path.as_ref())
1446 fn _create(&self, path: &Path) -> io::Result<()> {
1448 self.create_dir_all(path)
1450 self.inner.mkdir(path)
1454 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1455 if path == Path::new("") || path.is_dir() { return Ok(()) }
1456 if let Some(p) = path.parent() {
1457 try!(self.create_dir_all(p))
1459 self.inner.mkdir(path)
1463 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1464 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1471 #![allow(deprecated)] //rand
1477 use fs::{self, File, OpenOptions};
1478 use io::{ErrorKind, SeekFrom};
1480 use path::Path as Path2;
1481 use rand::{self, StdRng, Rng};
1484 macro_rules! check { ($e:expr) => (
1487 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1491 macro_rules! error { ($e:expr, $s:expr) => (
1493 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1494 Err(ref err) => assert!(err.to_string().contains($s),
1495 format!("`{}` did not contain `{}`", err, $s))
1499 pub struct TempDir(PathBuf);
1502 fn join(&self, path: &str) -> PathBuf {
1503 let TempDir(ref p) = *self;
1507 fn path<'a>(&'a self) -> &'a Path2 {
1508 let TempDir(ref p) = *self;
1513 impl Drop for TempDir {
1514 fn drop(&mut self) {
1515 // Gee, seeing how we're testing the fs module I sure hope that we
1516 // at least implement this correctly!
1517 let TempDir(ref p) = *self;
1518 check!(fs::remove_dir_all(p));
1522 pub fn tmpdir() -> TempDir {
1523 let p = env::temp_dir();
1524 let mut r = rand::thread_rng();
1525 let ret = p.join(&format!("rust-{}", r.next_u32()));
1526 check!(fs::create_dir(&ret));
1531 fn file_test_io_smoke_test() {
1532 let message = "it's alright. have a good time";
1533 let tmpdir = tmpdir();
1534 let filename = &tmpdir.join("file_rt_io_file_test.txt");
1536 let mut write_stream = check!(File::create(filename));
1537 check!(write_stream.write(message.as_bytes()));
1540 let mut read_stream = check!(File::open(filename));
1541 let mut read_buf = [0; 1028];
1542 let read_str = match check!(read_stream.read(&mut read_buf)) {
1543 0 => panic!("shouldn't happen"),
1544 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1546 assert_eq!(read_str, message);
1548 check!(fs::remove_file(filename));
1552 fn invalid_path_raises() {
1553 let tmpdir = tmpdir();
1554 let filename = &tmpdir.join("file_that_does_not_exist.txt");
1555 let result = File::open(filename);
1558 error!(result, "o such file or directory");
1560 // error!(result, "couldn't open path as file");
1561 // error!(result, format!("path={}; mode=open; access=read", filename.display()));
1565 fn file_test_iounlinking_invalid_path_should_raise_condition() {
1566 let tmpdir = tmpdir();
1567 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1569 let result = fs::remove_file(filename);
1572 error!(result, "o such file or directory");
1574 // error!(result, "couldn't unlink path");
1575 // error!(result, format!("path={}", filename.display()));
1579 fn file_test_io_non_positional_read() {
1580 let message: &str = "ten-four";
1581 let mut read_mem = [0; 8];
1582 let tmpdir = tmpdir();
1583 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1585 let mut rw_stream = check!(File::create(filename));
1586 check!(rw_stream.write(message.as_bytes()));
1589 let mut read_stream = check!(File::open(filename));
1591 let read_buf = &mut read_mem[0..4];
1592 check!(read_stream.read(read_buf));
1595 let read_buf = &mut read_mem[4..8];
1596 check!(read_stream.read(read_buf));
1599 check!(fs::remove_file(filename));
1600 let read_str = str::from_utf8(&read_mem).unwrap();
1601 assert_eq!(read_str, message);
1605 fn file_test_io_seek_and_tell_smoke_test() {
1606 let message = "ten-four";
1607 let mut read_mem = [0; 4];
1608 let set_cursor = 4 as u64;
1609 let tell_pos_pre_read;
1610 let tell_pos_post_read;
1611 let tmpdir = tmpdir();
1612 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1614 let mut rw_stream = check!(File::create(filename));
1615 check!(rw_stream.write(message.as_bytes()));
1618 let mut read_stream = check!(File::open(filename));
1619 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
1620 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
1621 check!(read_stream.read(&mut read_mem));
1622 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
1624 check!(fs::remove_file(filename));
1625 let read_str = str::from_utf8(&read_mem).unwrap();
1626 assert_eq!(read_str, &message[4..8]);
1627 assert_eq!(tell_pos_pre_read, set_cursor);
1628 assert_eq!(tell_pos_post_read, message.len() as u64);
1632 fn file_test_io_seek_and_write() {
1633 let initial_msg = "food-is-yummy";
1634 let overwrite_msg = "-the-bar!!";
1635 let final_msg = "foo-the-bar!!";
1637 let mut read_mem = [0; 13];
1638 let tmpdir = tmpdir();
1639 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1641 let mut rw_stream = check!(File::create(filename));
1642 check!(rw_stream.write(initial_msg.as_bytes()));
1643 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
1644 check!(rw_stream.write(overwrite_msg.as_bytes()));
1647 let mut read_stream = check!(File::open(filename));
1648 check!(read_stream.read(&mut read_mem));
1650 check!(fs::remove_file(filename));
1651 let read_str = str::from_utf8(&read_mem).unwrap();
1652 assert!(read_str == final_msg);
1656 fn file_test_io_seek_shakedown() {
1658 let initial_msg = "qwer-asdf-zxcv";
1659 let chunk_one: &str = "qwer";
1660 let chunk_two: &str = "asdf";
1661 let chunk_three: &str = "zxcv";
1662 let mut read_mem = [0; 4];
1663 let tmpdir = tmpdir();
1664 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1666 let mut rw_stream = check!(File::create(filename));
1667 check!(rw_stream.write(initial_msg.as_bytes()));
1670 let mut read_stream = check!(File::open(filename));
1672 check!(read_stream.seek(SeekFrom::End(-4)));
1673 check!(read_stream.read(&mut read_mem));
1674 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
1676 check!(read_stream.seek(SeekFrom::Current(-9)));
1677 check!(read_stream.read(&mut read_mem));
1678 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
1680 check!(read_stream.seek(SeekFrom::Start(0)));
1681 check!(read_stream.read(&mut read_mem));
1682 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
1684 check!(fs::remove_file(filename));
1688 fn file_test_stat_is_correct_on_is_file() {
1689 let tmpdir = tmpdir();
1690 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1692 let mut opts = OpenOptions::new();
1693 let mut fs = check!(opts.read(true).write(true)
1694 .create(true).open(filename));
1696 fs.write(msg.as_bytes()).unwrap();
1698 let fstat_res = check!(fs.metadata());
1699 assert!(fstat_res.is_file());
1701 let stat_res_fn = check!(fs::metadata(filename));
1702 assert!(stat_res_fn.is_file());
1703 let stat_res_meth = check!(filename.metadata());
1704 assert!(stat_res_meth.is_file());
1705 check!(fs::remove_file(filename));
1709 fn file_test_stat_is_correct_on_is_dir() {
1710 let tmpdir = tmpdir();
1711 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1712 check!(fs::create_dir(filename));
1713 let stat_res_fn = check!(fs::metadata(filename));
1714 assert!(stat_res_fn.is_dir());
1715 let stat_res_meth = check!(filename.metadata());
1716 assert!(stat_res_meth.is_dir());
1717 check!(fs::remove_dir(filename));
1721 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1722 let tmpdir = tmpdir();
1723 let dir = &tmpdir.join("fileinfo_false_on_dir");
1724 check!(fs::create_dir(dir));
1725 assert!(dir.is_file() == false);
1726 check!(fs::remove_dir(dir));
1730 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1731 let tmpdir = tmpdir();
1732 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1733 check!(check!(File::create(file)).write(b"foo"));
1734 assert!(file.exists());
1735 check!(fs::remove_file(file));
1736 assert!(!file.exists());
1740 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1741 let tmpdir = tmpdir();
1742 let dir = &tmpdir.join("before_and_after_dir");
1743 assert!(!dir.exists());
1744 check!(fs::create_dir(dir));
1745 assert!(dir.exists());
1746 assert!(dir.is_dir());
1747 check!(fs::remove_dir(dir));
1748 assert!(!dir.exists());
1752 fn file_test_directoryinfo_readdir() {
1753 let tmpdir = tmpdir();
1754 let dir = &tmpdir.join("di_readdir");
1755 check!(fs::create_dir(dir));
1758 let f = dir.join(&format!("{}.txt", n));
1759 let mut w = check!(File::create(&f));
1760 let msg_str = format!("{}{}", prefix, n.to_string());
1761 let msg = msg_str.as_bytes();
1762 check!(w.write(msg));
1764 let files = check!(fs::read_dir(dir));
1765 let mut mem = [0; 4];
1767 let f = f.unwrap().path();
1769 let n = f.file_stem().unwrap();
1770 check!(check!(File::open(&f)).read(&mut mem));
1771 let read_str = str::from_utf8(&mem).unwrap();
1772 let expected = format!("{}{}", prefix, n.to_str().unwrap());
1773 assert_eq!(expected, read_str);
1775 check!(fs::remove_file(&f));
1777 check!(fs::remove_dir(dir));
1781 fn file_test_walk_dir() {
1782 let tmpdir = tmpdir();
1783 let dir = &tmpdir.join("walk_dir");
1784 check!(fs::create_dir(dir));
1786 let dir1 = &dir.join("01/02/03");
1787 check!(fs::create_dir_all(dir1));
1788 check!(File::create(&dir1.join("04")));
1790 let dir2 = &dir.join("11/12/13");
1791 check!(fs::create_dir_all(dir2));
1792 check!(File::create(&dir2.join("14")));
1794 let files = check!(fs::walk_dir(dir));
1795 let mut cur = [0; 2];
1797 let f = f.unwrap().path();
1798 let stem = f.file_stem().unwrap().to_str().unwrap();
1799 let root = stem.as_bytes()[0] - b'0';
1800 let name = stem.as_bytes()[1] - b'0';
1801 assert!(cur[root as usize] < name);
1802 cur[root as usize] = name;
1805 check!(fs::remove_dir_all(dir));
1809 fn mkdir_path_already_exists_error() {
1810 let tmpdir = tmpdir();
1811 let dir = &tmpdir.join("mkdir_error_twice");
1812 check!(fs::create_dir(dir));
1813 let e = fs::create_dir(dir).err().unwrap();
1814 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
1818 fn recursive_mkdir() {
1819 let tmpdir = tmpdir();
1820 let dir = tmpdir.join("d1/d2");
1821 check!(fs::create_dir_all(&dir));
1822 assert!(dir.is_dir())
1826 fn recursive_mkdir_failure() {
1827 let tmpdir = tmpdir();
1828 let dir = tmpdir.join("d1");
1829 let file = dir.join("f1");
1831 check!(fs::create_dir_all(&dir));
1832 check!(File::create(&file));
1834 let result = fs::create_dir_all(&file);
1836 assert!(result.is_err());
1837 // error!(result, "couldn't recursively mkdir");
1838 // error!(result, "couldn't create directory");
1839 // error!(result, "mode=0700");
1840 // error!(result, format!("path={}", file.display()));
1844 fn recursive_mkdir_slash() {
1845 check!(fs::create_dir_all(&Path2::new("/")));
1848 // FIXME(#12795) depends on lstat to work on windows
1849 #[cfg(not(windows))]
1851 fn recursive_rmdir() {
1852 let tmpdir = tmpdir();
1853 let d1 = tmpdir.join("d1");
1854 let dt = d1.join("t");
1855 let dtt = dt.join("t");
1856 let d2 = tmpdir.join("d2");
1857 let canary = d2.join("do_not_delete");
1858 check!(fs::create_dir_all(&dtt));
1859 check!(fs::create_dir_all(&d2));
1860 check!(check!(File::create(&canary)).write(b"foo"));
1861 check!(fs::soft_link(&d2, &dt.join("d2")));
1862 check!(fs::remove_dir_all(&d1));
1864 assert!(!d1.is_dir());
1865 assert!(canary.exists());
1869 fn unicode_path_is_dir() {
1870 assert!(Path2::new(".").is_dir());
1871 assert!(!Path2::new("test/stdtest/fs.rs").is_dir());
1873 let tmpdir = tmpdir();
1875 let mut dirpath = tmpdir.path().to_path_buf();
1876 dirpath.push("test-가一ー你好");
1877 check!(fs::create_dir(&dirpath));
1878 assert!(dirpath.is_dir());
1880 let mut filepath = dirpath;
1881 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
1882 check!(File::create(&filepath)); // ignore return; touch only
1883 assert!(!filepath.is_dir());
1884 assert!(filepath.exists());
1888 fn unicode_path_exists() {
1889 assert!(Path2::new(".").exists());
1890 assert!(!Path2::new("test/nonexistent-bogus-path").exists());
1892 let tmpdir = tmpdir();
1893 let unicode = tmpdir.path();
1894 let unicode = unicode.join(&format!("test-각丁ー再见"));
1895 check!(fs::create_dir(&unicode));
1896 assert!(unicode.exists());
1897 assert!(!Path2::new("test/unicode-bogus-path-각丁ー再见").exists());
1901 fn copy_file_does_not_exist() {
1902 let from = Path2::new("test/nonexistent-bogus-path");
1903 let to = Path2::new("test/other-bogus-path");
1905 match fs::copy(&from, &to) {
1908 assert!(!from.exists());
1909 assert!(!to.exists());
1915 fn copy_src_does_not_exist() {
1916 let tmpdir = tmpdir();
1917 let from = Path2::new("test/nonexistent-bogus-path");
1918 let to = tmpdir.join("out.txt");
1919 check!(check!(File::create(&to)).write(b"hello"));
1920 assert!(fs::copy(&from, &to).is_err());
1921 assert!(!from.exists());
1922 let mut v = Vec::new();
1923 check!(check!(File::open(&to)).read_to_end(&mut v));
1924 assert_eq!(v, b"hello");
1929 let tmpdir = tmpdir();
1930 let input = tmpdir.join("in.txt");
1931 let out = tmpdir.join("out.txt");
1933 check!(check!(File::create(&input)).write(b"hello"));
1934 check!(fs::copy(&input, &out));
1935 let mut v = Vec::new();
1936 check!(check!(File::open(&out)).read_to_end(&mut v));
1937 assert_eq!(v, b"hello");
1939 assert_eq!(check!(input.metadata()).permissions(),
1940 check!(out.metadata()).permissions());
1944 fn copy_file_dst_dir() {
1945 let tmpdir = tmpdir();
1946 let out = tmpdir.join("out");
1948 check!(File::create(&out));
1949 match fs::copy(&*out, tmpdir.path()) {
1950 Ok(..) => panic!(), Err(..) => {}
1955 fn copy_file_dst_exists() {
1956 let tmpdir = tmpdir();
1957 let input = tmpdir.join("in");
1958 let output = tmpdir.join("out");
1960 check!(check!(File::create(&input)).write("foo".as_bytes()));
1961 check!(check!(File::create(&output)).write("bar".as_bytes()));
1962 check!(fs::copy(&input, &output));
1964 let mut v = Vec::new();
1965 check!(check!(File::open(&output)).read_to_end(&mut v));
1966 assert_eq!(v, b"foo".to_vec());
1970 fn copy_file_src_dir() {
1971 let tmpdir = tmpdir();
1972 let out = tmpdir.join("out");
1974 match fs::copy(tmpdir.path(), &out) {
1975 Ok(..) => panic!(), Err(..) => {}
1977 assert!(!out.exists());
1981 fn copy_file_preserves_perm_bits() {
1982 let tmpdir = tmpdir();
1983 let input = tmpdir.join("in.txt");
1984 let out = tmpdir.join("out.txt");
1986 let attr = check!(check!(File::create(&input)).metadata());
1987 let mut p = attr.permissions();
1988 p.set_readonly(true);
1989 check!(fs::set_permissions(&input, p));
1990 check!(fs::copy(&input, &out));
1991 assert!(check!(out.metadata()).permissions().readonly());
1992 check!(fs::set_permissions(&input, attr.permissions()));
1993 check!(fs::set_permissions(&out, attr.permissions()));
1998 fn copy_file_preserves_streams() {
2000 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2001 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 6);
2002 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2003 let mut v = Vec::new();
2004 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2005 assert_eq!(v, b"carrot".to_vec());
2008 #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
2010 fn symlinks_work() {
2011 let tmpdir = tmpdir();
2012 let input = tmpdir.join("in.txt");
2013 let out = tmpdir.join("out.txt");
2015 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2016 check!(fs::soft_link(&input, &out));
2017 // if cfg!(not(windows)) {
2018 // assert_eq!(check!(lstat(&out)).kind, FileType::Symlink);
2019 // assert_eq!(check!(out.lstat()).kind, FileType::Symlink);
2021 assert_eq!(check!(fs::metadata(&out)).len(),
2022 check!(fs::metadata(&input)).len());
2023 let mut v = Vec::new();
2024 check!(check!(File::open(&out)).read_to_end(&mut v));
2025 assert_eq!(v, b"foobar".to_vec());
2028 #[cfg(not(windows))] // apparently windows doesn't like symlinks
2030 fn symlink_noexist() {
2031 let tmpdir = tmpdir();
2032 // symlinks can point to things that don't exist
2033 check!(fs::soft_link(&tmpdir.join("foo"), &tmpdir.join("bar")));
2034 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))),
2035 tmpdir.join("foo"));
2039 fn readlink_not_symlink() {
2040 let tmpdir = tmpdir();
2041 match fs::read_link(tmpdir.path()) {
2042 Ok(..) => panic!("wanted a failure"),
2049 let tmpdir = tmpdir();
2050 let input = tmpdir.join("in.txt");
2051 let out = tmpdir.join("out.txt");
2053 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2054 check!(fs::hard_link(&input, &out));
2055 assert_eq!(check!(fs::metadata(&out)).len(),
2056 check!(fs::metadata(&input)).len());
2057 assert_eq!(check!(fs::metadata(&out)).len(),
2058 check!(input.metadata()).len());
2059 let mut v = Vec::new();
2060 check!(check!(File::open(&out)).read_to_end(&mut v));
2061 assert_eq!(v, b"foobar".to_vec());
2063 // can't link to yourself
2064 match fs::hard_link(&input, &input) {
2065 Ok(..) => panic!("wanted a failure"),
2068 // can't link to something that doesn't exist
2069 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
2070 Ok(..) => panic!("wanted a failure"),
2077 let tmpdir = tmpdir();
2078 let file = tmpdir.join("in.txt");
2080 check!(File::create(&file));
2081 let attr = check!(fs::metadata(&file));
2082 assert!(!attr.permissions().readonly());
2083 let mut p = attr.permissions();
2084 p.set_readonly(true);
2085 check!(fs::set_permissions(&file, p.clone()));
2086 let attr = check!(fs::metadata(&file));
2087 assert!(attr.permissions().readonly());
2089 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
2090 Ok(..) => panic!("wanted an error"),
2094 p.set_readonly(false);
2095 check!(fs::set_permissions(&file, p));
2099 fn sync_doesnt_kill_anything() {
2100 let tmpdir = tmpdir();
2101 let path = tmpdir.join("in.txt");
2103 let mut file = check!(File::create(&path));
2104 check!(file.sync_all());
2105 check!(file.sync_data());
2106 check!(file.write(b"foo"));
2107 check!(file.sync_all());
2108 check!(file.sync_data());
2112 fn truncate_works() {
2113 let tmpdir = tmpdir();
2114 let path = tmpdir.join("in.txt");
2116 let mut file = check!(File::create(&path));
2117 check!(file.write(b"foo"));
2118 check!(file.sync_all());
2120 // Do some simple things with truncation
2121 assert_eq!(check!(file.metadata()).len(), 3);
2122 check!(file.set_len(10));
2123 assert_eq!(check!(file.metadata()).len(), 10);
2124 check!(file.write(b"bar"));
2125 check!(file.sync_all());
2126 assert_eq!(check!(file.metadata()).len(), 10);
2128 let mut v = Vec::new();
2129 check!(check!(File::open(&path)).read_to_end(&mut v));
2130 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
2132 // Truncate to a smaller length, don't seek, and then write something.
2133 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
2134 // past the end of the file).
2135 check!(file.set_len(2));
2136 assert_eq!(check!(file.metadata()).len(), 2);
2137 check!(file.write(b"wut"));
2138 check!(file.sync_all());
2139 assert_eq!(check!(file.metadata()).len(), 9);
2140 let mut v = Vec::new();
2141 check!(check!(File::open(&path)).read_to_end(&mut v));
2142 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
2147 use fs::OpenOptions as OO;
2148 fn c<T: Clone>(t: &T) -> T { t.clone() }
2150 let tmpdir = tmpdir();
2152 let mut r = OO::new(); r.read(true);
2153 let mut w = OO::new(); w.write(true);
2154 let mut rw = OO::new(); rw.read(true).write(true);
2155 let mut a = OO::new(); a.append(true);
2156 let mut ra = OO::new(); ra.read(true).append(true);
2158 let invalid_options = if cfg!(windows) { "The parameter is incorrect" }
2159 else { "Invalid argument" };
2161 // Test various combinations of creation modes and access modes.
2164 // creation mode | read | write | read-write | append | read-append |
2165 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
2166 // not set (open existing) | X | X | X | X | X |
2167 // create | | X | X | X | X |
2168 // truncate | | X | X | | |
2169 // create and truncate | | X | X | | |
2170 // create_new | | X | X | X | X |
2172 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
2175 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
2176 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
2177 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
2178 check!(c(&w).create(true).open(&tmpdir.join("a")));
2179 check!(c(&w).open(&tmpdir.join("a")));
2182 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
2183 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
2184 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
2185 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
2186 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
2189 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
2190 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
2191 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
2192 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2193 check!(c(&rw).open(&tmpdir.join("c")));
2196 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
2197 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
2198 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
2199 check!(c(&a).create(true).open(&tmpdir.join("d")));
2200 check!(c(&a).open(&tmpdir.join("d")));
2203 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
2204 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
2205 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
2206 check!(c(&ra).create(true).open(&tmpdir.join("e")));
2207 check!(c(&ra).open(&tmpdir.join("e")));
2209 // Test opening a file without setting an access mode
2210 let mut blank = OO::new();
2211 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
2214 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
2216 // Test write fails for read-only
2217 check!(r.open(&tmpdir.join("h")));
2219 let mut f = check!(r.open(&tmpdir.join("h")));
2220 assert!(f.write("wut".as_bytes()).is_err());
2223 // Test write overwrites
2225 let mut f = check!(c(&w).open(&tmpdir.join("h")));
2226 check!(f.write("baz".as_bytes()));
2229 let mut f = check!(c(&r).open(&tmpdir.join("h")));
2230 let mut b = vec![0; 6];
2231 check!(f.read(&mut b));
2232 assert_eq!(b, "bazbar".as_bytes());
2235 // Test truncate works
2237 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
2238 check!(f.write("foo".as_bytes()));
2240 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2242 // Test append works
2243 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2245 let mut f = check!(c(&a).open(&tmpdir.join("h")));
2246 check!(f.write("bar".as_bytes()));
2248 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
2250 // Test .append(true) equals .write(true).append(true)
2252 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
2253 check!(f.write("baz".as_bytes()));
2255 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
2260 let mut bytes = [0; 1024];
2261 StdRng::new().unwrap().fill_bytes(&mut bytes);
2263 let tmpdir = tmpdir();
2265 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
2266 let mut v = Vec::new();
2267 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
2268 assert!(v == &bytes[..]);
2272 #[cfg(not(windows))]
2273 fn unlink_readonly() {
2274 let tmpdir = tmpdir();
2275 let path = tmpdir.join("file");
2276 check!(File::create(&path));
2277 let mut perm = check!(fs::metadata(&path)).permissions();
2278 perm.set_readonly(true);
2279 check!(fs::set_permissions(&path, perm));
2280 check!(fs::remove_file(&path));
2284 fn mkdir_trailing_slash() {
2285 let tmpdir = tmpdir();
2286 let path = tmpdir.join("file");
2287 check!(fs::create_dir_all(&path.join("a/")));
2291 fn canonicalize_works_simple() {
2292 let tmpdir = tmpdir();
2293 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2294 let file = tmpdir.join("test");
2295 File::create(&file).unwrap();
2296 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2300 #[cfg(not(windows))]
2301 fn realpath_works() {
2302 let tmpdir = tmpdir();
2303 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2304 let file = tmpdir.join("test");
2305 let dir = tmpdir.join("test2");
2306 let link = dir.join("link");
2307 let linkdir = tmpdir.join("test3");
2309 File::create(&file).unwrap();
2310 fs::create_dir(&dir).unwrap();
2311 fs::soft_link(&file, &link).unwrap();
2312 fs::soft_link(&dir, &linkdir).unwrap();
2314 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
2316 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
2317 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2318 assert_eq!(fs::canonicalize(&link).unwrap(), file);
2319 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
2320 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
2324 #[cfg(not(windows))]
2325 fn realpath_works_tricky() {
2326 let tmpdir = tmpdir();
2327 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2329 let a = tmpdir.join("a");
2330 let b = a.join("b");
2331 let c = b.join("c");
2332 let d = a.join("d");
2333 let e = d.join("e");
2334 let f = a.join("f");
2336 fs::create_dir_all(&b).unwrap();
2337 fs::create_dir_all(&d).unwrap();
2338 File::create(&f).unwrap();
2339 fs::soft_link("../d/e", &c).unwrap();
2340 fs::soft_link("../f", &e).unwrap();
2342 assert_eq!(fs::canonicalize(&c).unwrap(), f);
2343 assert_eq!(fs::canonicalize(&e).unwrap(), f);
2347 fn dir_entry_methods() {
2348 let tmpdir = tmpdir();
2350 fs::create_dir_all(&tmpdir.join("a")).unwrap();
2351 File::create(&tmpdir.join("b")).unwrap();
2353 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
2354 let fname = file.file_name();
2355 match fname.to_str() {
2357 assert!(file.file_type().unwrap().is_dir());
2358 assert!(file.metadata().unwrap().is_dir());
2361 assert!(file.file_type().unwrap().is_file());
2362 assert!(file.metadata().unwrap().is_file());
2364 f => panic!("unknown file name: {:?}", f),
2370 fn read_dir_not_found() {
2371 let res = fs::read_dir("/path/that/does/not/exist");
2372 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);