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::{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.
35 /// Files are automatically closed when they go out of scope.
40 /// use std::io::prelude::*;
41 /// use std::fs::File;
43 /// # fn foo() -> std::io::Result<()> {
44 /// let mut f = try!(File::create("foo.txt"));
45 /// try!(f.write_all(b"Hello, world!"));
47 /// let mut f = try!(File::open("foo.txt"));
48 /// let mut s = String::new();
49 /// try!(f.read_to_string(&mut s));
50 /// assert_eq!(s, "Hello, world!");
54 #[stable(feature = "rust1", since = "1.0.0")]
59 /// Metadata information about a file.
61 /// This structure is returned from the [`metadata`] function or method and
62 /// represents known metadata about a file such as its permissions, size,
63 /// modification times, etc.
65 /// [`metadata`]: fn.metadata.html
66 #[stable(feature = "rust1", since = "1.0.0")]
68 pub struct Metadata(fs_imp::FileAttr);
70 /// Iterator over the entries in a directory.
72 /// This iterator is returned from the [`read_dir`] function of this module and
73 /// will yield instances of `io::Result<DirEntry>`. Through a [`DirEntry`]
74 /// information like the entry's path and possibly other metadata can be
77 /// [`read_dir`]: fn.read_dir.html
78 /// [`DirEntry`]: struct.DirEntry.html
82 /// This [`io::Result`] will be an `Err` if there's some sort of intermittent
83 /// IO error during iteration.
85 /// [`io::Result`]: ../io/type.Result.html
86 #[stable(feature = "rust1", since = "1.0.0")]
87 pub struct ReadDir(fs_imp::ReadDir);
89 /// Entries returned by the [`ReadDir`] iterator.
91 /// [`ReadDir`]: struct.ReadDir.html
93 /// An instance of `DirEntry` represents an entry inside of a directory on the
94 /// filesystem. Each entry can be inspected via methods to learn about the full
95 /// path or possibly other metadata through per-platform extension traits.
96 #[stable(feature = "rust1", since = "1.0.0")]
97 pub struct DirEntry(fs_imp::DirEntry);
99 /// Options and flags which can be used to configure how a file is opened.
101 /// This builder exposes the ability to configure how a [`File`] is opened and
102 /// what operations are permitted on the open file. The [`File::open`] and
103 /// [`File::create`] methods are aliases for commonly used options using this
106 /// [`File`]: struct.File.html
107 /// [`File::open`]: struct.File.html#method.open
108 /// [`File::create`]: struct.File.html#method.create
110 /// Generally speaking, when using `OpenOptions`, you'll first call [`new()`],
111 /// then chain calls to methods to set each option, then call [`open()`],
112 /// passing the path of the file you're trying to open. This will give you a
113 /// [`io::Result`][result] with a [`File`][file] inside that you can further
116 /// [`new()`]: struct.OpenOptions.html#method.new
117 /// [`open()`]: struct.OpenOptions.html#method.open
118 /// [result]: ../io/type.Result.html
119 /// [file]: struct.File.html
123 /// Opening a file to read:
126 /// use std::fs::OpenOptions;
128 /// let file = OpenOptions::new().read(true).open("foo.txt");
131 /// Opening a file for both reading and writing, as well as creating it if it
135 /// use std::fs::OpenOptions;
137 /// let file = OpenOptions::new()
141 /// .open("foo.txt");
144 #[stable(feature = "rust1", since = "1.0.0")]
145 pub struct OpenOptions(fs_imp::OpenOptions);
147 /// Representation of the various permissions on a file.
149 /// This module only currently provides one bit of information, [`readonly`],
150 /// which is exposed on all currently supported platforms. Unix-specific
151 /// functionality, such as mode bits, is available through the
152 /// `os::unix::PermissionsExt` trait.
154 /// [`readonly`]: struct.Permissions.html#method.readonly
155 #[derive(Clone, PartialEq, Eq, Debug)]
156 #[stable(feature = "rust1", since = "1.0.0")]
157 pub struct Permissions(fs_imp::FilePermissions);
159 /// A structure representing a type of file with accessors for each file type.
160 /// It is returned by [`Metadata::file_type`] method.
162 /// [`Metadata::file_type`]: struct.Metadata.html#method.file_type
163 #[stable(feature = "file_type", since = "1.1.0")]
164 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
165 pub struct FileType(fs_imp::FileType);
167 /// A builder used to create directories in various manners.
169 /// This builder also supports platform-specific options.
170 #[stable(feature = "dir_builder", since = "1.6.0")]
171 pub struct DirBuilder {
172 inner: fs_imp::DirBuilder,
177 /// Attempts to open a file in read-only mode.
179 /// See the [`OpenOptions::open`] method for more details.
183 /// This function will return an error if `path` does not already exist.
184 /// Other errors may also be returned according to [`OpenOptions::open`].
186 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
191 /// use std::fs::File;
193 /// # fn foo() -> std::io::Result<()> {
194 /// let mut f = try!(File::open("foo.txt"));
198 #[stable(feature = "rust1", since = "1.0.0")]
199 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
200 OpenOptions::new().read(true).open(path.as_ref())
203 /// Opens a file in write-only mode.
205 /// This function will create a file if it does not exist,
206 /// and will truncate it if it does.
208 /// See the [`OpenOptions::open`] function for more details.
210 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
215 /// use std::fs::File;
217 /// # fn foo() -> std::io::Result<()> {
218 /// let mut f = try!(File::create("foo.txt"));
222 #[stable(feature = "rust1", since = "1.0.0")]
223 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
224 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
227 /// Attempts to sync all OS-internal metadata to disk.
229 /// This function will attempt to ensure that all in-core data reaches the
230 /// filesystem before returning.
235 /// use std::fs::File;
236 /// use std::io::prelude::*;
238 /// # fn foo() -> std::io::Result<()> {
239 /// let mut f = try!(File::create("foo.txt"));
240 /// try!(f.write_all(b"Hello, world!"));
242 /// try!(f.sync_all());
246 #[stable(feature = "rust1", since = "1.0.0")]
247 pub fn sync_all(&self) -> io::Result<()> {
251 /// This function is similar to [`sync_all`], except that it may not
252 /// synchronize file metadata to the filesystem.
254 /// This is intended for use cases that must synchronize content, but don't
255 /// need the metadata on disk. The goal of this method is to reduce disk
258 /// Note that some platforms may simply implement this in terms of
261 /// [`sync_all`]: struct.File.html#method.sync_all
266 /// use std::fs::File;
267 /// use std::io::prelude::*;
269 /// # fn foo() -> std::io::Result<()> {
270 /// let mut f = try!(File::create("foo.txt"));
271 /// try!(f.write_all(b"Hello, world!"));
273 /// try!(f.sync_data());
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub fn sync_data(&self) -> io::Result<()> {
279 self.inner.datasync()
282 /// Truncates or extends the underlying file, updating the size of
283 /// this file to become `size`.
285 /// If the `size` is less than the current file's size, then the file will
286 /// be shrunk. If it is greater than the current file's size, then the file
287 /// will be extended to `size` and have all of the intermediate data filled
292 /// This function will return an error if the file is not opened for writing.
297 /// use std::fs::File;
299 /// # fn foo() -> std::io::Result<()> {
300 /// let mut f = try!(File::create("foo.txt"));
301 /// try!(f.set_len(10));
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub fn set_len(&self, size: u64) -> io::Result<()> {
307 self.inner.truncate(size)
310 /// Queries metadata about the underlying file.
315 /// use std::fs::File;
317 /// # fn foo() -> std::io::Result<()> {
318 /// let mut f = try!(File::open("foo.txt"));
319 /// let metadata = try!(f.metadata());
323 #[stable(feature = "rust1", since = "1.0.0")]
324 pub fn metadata(&self) -> io::Result<Metadata> {
325 self.inner.file_attr().map(Metadata)
328 /// Creates a new independently owned handle to the underlying file.
330 /// The returned `File` is a reference to the same state that this object
331 /// references. Both handles will read and write with the same cursor
337 /// use std::fs::File;
339 /// # fn foo() -> std::io::Result<()> {
340 /// let mut f = try!(File::open("foo.txt"));
341 /// let file_copy = try!(f.try_clone());
345 #[stable(feature = "file_try_clone", since = "1.9.0")]
346 pub fn try_clone(&self) -> io::Result<File> {
348 inner: self.inner.duplicate()?
353 impl AsInner<fs_imp::File> for File {
354 fn as_inner(&self) -> &fs_imp::File { &self.inner }
356 impl FromInner<fs_imp::File> for File {
357 fn from_inner(f: fs_imp::File) -> File {
361 impl IntoInner<fs_imp::File> for File {
362 fn into_inner(self) -> fs_imp::File {
367 #[stable(feature = "rust1", since = "1.0.0")]
368 impl fmt::Debug for File {
369 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
374 #[stable(feature = "rust1", since = "1.0.0")]
376 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
379 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
380 self.inner.read_to_end(buf)
383 #[stable(feature = "rust1", since = "1.0.0")]
384 impl Write for File {
385 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
386 self.inner.write(buf)
388 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
390 #[stable(feature = "rust1", since = "1.0.0")]
392 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
396 #[stable(feature = "rust1", since = "1.0.0")]
397 impl<'a> Read for &'a File {
398 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
401 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
402 self.inner.read_to_end(buf)
405 #[stable(feature = "rust1", since = "1.0.0")]
406 impl<'a> Write for &'a File {
407 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
408 self.inner.write(buf)
410 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
412 #[stable(feature = "rust1", since = "1.0.0")]
413 impl<'a> Seek for &'a File {
414 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
420 /// Creates a blank new set of options ready for configuration.
422 /// All options are initially set to `false`.
427 /// use std::fs::OpenOptions;
429 /// let mut options = OpenOptions::new();
430 /// let file = options.read(true).open("foo.txt");
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn new() -> OpenOptions {
434 OpenOptions(fs_imp::OpenOptions::new())
437 /// Sets the option for read access.
439 /// This option, when true, will indicate that the file should be
440 /// `read`-able if opened.
445 /// use std::fs::OpenOptions;
447 /// let file = OpenOptions::new().read(true).open("foo.txt");
449 #[stable(feature = "rust1", since = "1.0.0")]
450 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
451 self.0.read(read); self
454 /// Sets the option for write access.
456 /// This option, when true, will indicate that the file should be
457 /// `write`-able if opened.
459 /// If the file already exists, any write calls on it will overwrite its
460 /// contents, without truncating it.
465 /// use std::fs::OpenOptions;
467 /// let file = OpenOptions::new().write(true).open("foo.txt");
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
471 self.0.write(write); self
474 /// Sets the option for the append mode.
476 /// This option, when true, means that writes will append to a file instead
477 /// of overwriting previous contents.
478 /// Note that setting `.write(true).append(true)` has the same effect as
479 /// setting only `.append(true)`.
481 /// For most filesystems, the operating system guarantees that all writes are
482 /// atomic: no writes get mangled because another process writes at the same
485 /// One maybe obvious note when using append-mode: make sure that all data
486 /// that belongs together is written to the file in one operation. This
487 /// can be done by concatenating strings before passing them to `write()`,
488 /// or using a buffered writer (with a buffer of adequate size),
489 /// and calling `flush()` when the message is complete.
491 /// If a file is opened with both read and append access, beware that after
492 /// opening, and after every write, the position for reading may be set at the
493 /// end of the file. So, before writing, save the current position (using
494 /// `seek(SeekFrom::Current(0))`, and restore it before the next read.
499 /// use std::fs::OpenOptions;
501 /// let file = OpenOptions::new().append(true).open("foo.txt");
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
505 self.0.append(append); self
508 /// Sets the option for truncating a previous file.
510 /// If a file is successfully opened with this option set it will truncate
511 /// the file to 0 length if it already exists.
513 /// The file must be opened with write access for truncate to work.
518 /// use std::fs::OpenOptions;
520 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
522 #[stable(feature = "rust1", since = "1.0.0")]
523 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
524 self.0.truncate(truncate); self
527 /// Sets the option for creating a new file.
529 /// This option indicates whether a new file will be created if the file
530 /// does not yet already exist.
532 /// In order for the file to be created, `write` or `append` access must
538 /// use std::fs::OpenOptions;
540 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
542 #[stable(feature = "rust1", since = "1.0.0")]
543 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
544 self.0.create(create); self
547 /// Sets the option to always create a new file.
549 /// This option indicates whether a new file will be created.
550 /// No file is allowed to exist at the target location, also no (dangling)
553 /// This option is useful because it is atomic. Otherwise between checking
554 /// whether a file exists and creating a new one, the file may have been
555 /// created by another process (a TOCTOU race condition / attack).
557 /// If `.create_new(true)` is set, `.create()` and `.truncate()` are
560 /// The file must be opened with write or append access in order to create
566 /// use std::fs::OpenOptions;
568 /// let file = OpenOptions::new().write(true)
569 /// .create_new(true)
570 /// .open("foo.txt");
572 #[stable(feature = "expand_open_options2", since = "1.9.0")]
573 pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
574 self.0.create_new(create_new); self
577 /// Opens a file at `path` with the options specified by `self`.
581 /// This function will return an error under a number of different
582 /// circumstances, to include but not limited to:
584 /// * Opening a file that does not exist without setting `create` or
586 /// * Attempting to open a file with access that the user lacks
588 /// * Filesystem-level errors (full disk, etc)
589 /// * Invalid combinations of open options (truncate without write access,
590 /// no access mode set, etc)
595 /// use std::fs::OpenOptions;
597 /// let file = OpenOptions::new().open("foo.txt");
599 #[stable(feature = "rust1", since = "1.0.0")]
600 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
601 self._open(path.as_ref())
604 fn _open(&self, path: &Path) -> io::Result<File> {
605 let inner = fs_imp::File::open(path, &self.0)?;
606 Ok(File { inner: inner })
610 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
611 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
615 /// Returns the file type for this metadata.
620 /// # fn foo() -> std::io::Result<()> {
623 /// let metadata = try!(fs::metadata("foo.txt"));
625 /// println!("{:?}", metadata.file_type());
629 #[stable(feature = "file_type", since = "1.1.0")]
630 pub fn file_type(&self) -> FileType {
631 FileType(self.0.file_type())
634 /// Returns whether this metadata is for a directory.
639 /// # fn foo() -> std::io::Result<()> {
642 /// let metadata = try!(fs::metadata("foo.txt"));
644 /// assert!(!metadata.is_dir());
648 #[stable(feature = "rust1", since = "1.0.0")]
649 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
651 /// Returns whether this metadata is for a regular file.
656 /// # fn foo() -> std::io::Result<()> {
659 /// let metadata = try!(fs::metadata("foo.txt"));
661 /// assert!(metadata.is_file());
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn is_file(&self) -> bool { self.file_type().is_file() }
668 /// Returns the size of the file, in bytes, this metadata is for.
673 /// # fn foo() -> std::io::Result<()> {
676 /// let metadata = try!(fs::metadata("foo.txt"));
678 /// assert_eq!(0, metadata.len());
682 #[stable(feature = "rust1", since = "1.0.0")]
683 pub fn len(&self) -> u64 { self.0.size() }
685 /// Returns the permissions of the file this metadata is for.
690 /// # fn foo() -> std::io::Result<()> {
693 /// let metadata = try!(fs::metadata("foo.txt"));
695 /// assert!(!metadata.permissions().readonly());
699 #[stable(feature = "rust1", since = "1.0.0")]
700 pub fn permissions(&self) -> Permissions {
701 Permissions(self.0.perm())
704 /// Returns the last modification time listed in this metadata.
706 /// The returned value corresponds to the `mtime` field of `stat` on Unix
707 /// platforms and the `ftLastWriteTime` field on Windows platforms.
711 /// This field may not be available on all platforms, and will return an
712 /// `Err` on platforms where it is not available.
717 /// # fn foo() -> std::io::Result<()> {
720 /// let metadata = try!(fs::metadata("foo.txt"));
722 /// if let Ok(time) = metadata.modified() {
723 /// println!("{:?}", time);
725 /// println!("Not supported on this platform");
730 #[stable(feature = "fs_time", since = "1.10.0")]
731 pub fn modified(&self) -> io::Result<SystemTime> {
732 self.0.modified().map(FromInner::from_inner)
735 /// Returns the last access time of this metadata.
737 /// The returned value corresponds to the `atime` field of `stat` on Unix
738 /// platforms and the `ftLastAccessTime` field on Windows platforms.
740 /// Note that not all platforms will keep this field update in a file's
741 /// metadata, for example Windows has an option to disable updating this
742 /// time when files are accessed and Linux similarly has `noatime`.
746 /// This field may not be available on all platforms, and will return an
747 /// `Err` on platforms where it is not available.
752 /// # fn foo() -> std::io::Result<()> {
755 /// let metadata = try!(fs::metadata("foo.txt"));
757 /// if let Ok(time) = metadata.accessed() {
758 /// println!("{:?}", time);
760 /// println!("Not supported on this platform");
765 #[stable(feature = "fs_time", since = "1.10.0")]
766 pub fn accessed(&self) -> io::Result<SystemTime> {
767 self.0.accessed().map(FromInner::from_inner)
770 /// Returns the creation time listed in the this metadata.
772 /// The returned value corresponds to the `birthtime` field of `stat` on
773 /// Unix platforms and the `ftCreationTime` field on Windows platforms.
777 /// This field may not be available on all platforms, and will return an
778 /// `Err` on platforms where it is not available.
783 /// # fn foo() -> std::io::Result<()> {
786 /// let metadata = try!(fs::metadata("foo.txt"));
788 /// if let Ok(time) = metadata.created() {
789 /// println!("{:?}", time);
791 /// println!("Not supported on this platform");
796 #[stable(feature = "fs_time", since = "1.10.0")]
797 pub fn created(&self) -> io::Result<SystemTime> {
798 self.0.created().map(FromInner::from_inner)
802 impl AsInner<fs_imp::FileAttr> for Metadata {
803 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
807 /// Returns whether these permissions describe a readonly file.
812 /// use std::fs::File;
814 /// # fn foo() -> std::io::Result<()> {
815 /// let mut f = try!(File::create("foo.txt"));
816 /// let metadata = try!(f.metadata());
818 /// assert_eq!(false, metadata.permissions().readonly());
822 #[stable(feature = "rust1", since = "1.0.0")]
823 pub fn readonly(&self) -> bool { self.0.readonly() }
825 /// Modifies the readonly flag for this set of permissions.
827 /// This operation does **not** modify the filesystem. To modify the
828 /// filesystem use the `fs::set_permissions` function.
833 /// use std::fs::File;
835 /// # fn foo() -> std::io::Result<()> {
836 /// let f = try!(File::create("foo.txt"));
837 /// let metadata = try!(f.metadata());
838 /// let mut permissions = metadata.permissions();
840 /// permissions.set_readonly(true);
842 /// // filesystem doesn't change
843 /// assert_eq!(false, metadata.permissions().readonly());
845 /// // just this particular `permissions`.
846 /// assert_eq!(true, permissions.readonly());
850 #[stable(feature = "rust1", since = "1.0.0")]
851 pub fn set_readonly(&mut self, readonly: bool) {
852 self.0.set_readonly(readonly)
857 /// Test whether this file type represents a directory.
862 /// # fn foo() -> std::io::Result<()> {
865 /// let metadata = try!(fs::metadata("foo.txt"));
866 /// let file_type = metadata.file_type();
868 /// assert_eq!(file_type.is_dir(), false);
872 #[stable(feature = "file_type", since = "1.1.0")]
873 pub fn is_dir(&self) -> bool { self.0.is_dir() }
875 /// Test whether this file type represents a regular file.
880 /// # fn foo() -> std::io::Result<()> {
883 /// let metadata = try!(fs::metadata("foo.txt"));
884 /// let file_type = metadata.file_type();
886 /// assert_eq!(file_type.is_file(), true);
890 #[stable(feature = "file_type", since = "1.1.0")]
891 pub fn is_file(&self) -> bool { self.0.is_file() }
893 /// Test whether this file type represents a symbolic link.
898 /// # fn foo() -> std::io::Result<()> {
901 /// let metadata = try!(fs::metadata("foo.txt"));
902 /// let file_type = metadata.file_type();
904 /// assert_eq!(file_type.is_symlink(), false);
908 #[stable(feature = "file_type", since = "1.1.0")]
909 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
912 impl AsInner<fs_imp::FileType> for FileType {
913 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
916 impl FromInner<fs_imp::FilePermissions> for Permissions {
917 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
922 impl AsInner<fs_imp::FilePermissions> for Permissions {
923 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
926 #[stable(feature = "rust1", since = "1.0.0")]
927 impl Iterator for ReadDir {
928 type Item = io::Result<DirEntry>;
930 fn next(&mut self) -> Option<io::Result<DirEntry>> {
931 self.0.next().map(|entry| entry.map(DirEntry))
936 /// Returns the full path to the file that this entry represents.
938 /// The full path is created by joining the original path to `read_dir`
939 /// with the filename of this entry.
945 /// # fn foo() -> std::io::Result<()> {
946 /// for entry in try!(fs::read_dir(".")) {
947 /// let dir = try!(entry);
948 /// println!("{:?}", dir.path());
954 /// This prints output like:
959 /// "./hello_world.rs"
962 /// The exact text, of course, depends on what files you have in `.`.
963 #[stable(feature = "rust1", since = "1.0.0")]
964 pub fn path(&self) -> PathBuf { self.0.path() }
966 /// Return the metadata for the file that this entry points at.
968 /// This function will not traverse symlinks if this entry points at a
971 /// # Platform-specific behavior
973 /// On Windows this function is cheap to call (no extra system calls
974 /// needed), but on Unix platforms this function is the equivalent of
975 /// calling `symlink_metadata` on the path.
982 /// if let Ok(entries) = fs::read_dir(".") {
983 /// for entry in entries {
984 /// if let Ok(entry) = entry {
985 /// // Here, `entry` is a `DirEntry`.
986 /// if let Ok(metadata) = entry.metadata() {
987 /// // Now let's show our entry's permissions!
988 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
990 /// println!("Couldn't get metadata for {:?}", entry.path());
996 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
997 pub fn metadata(&self) -> io::Result<Metadata> {
998 self.0.metadata().map(Metadata)
1001 /// Return the file type for the file that this entry points at.
1003 /// This function will not traverse symlinks if this entry points at a
1006 /// # Platform-specific behavior
1008 /// On Windows and most Unix platforms this function is free (no extra
1009 /// system calls needed), but some Unix platforms may require the equivalent
1010 /// call to `symlink_metadata` to learn about the target file type.
1017 /// if let Ok(entries) = fs::read_dir(".") {
1018 /// for entry in entries {
1019 /// if let Ok(entry) = entry {
1020 /// // Here, `entry` is a `DirEntry`.
1021 /// if let Ok(file_type) = entry.file_type() {
1022 /// // Now let's show our entry's file type!
1023 /// println!("{:?}: {:?}", entry.path(), file_type);
1025 /// println!("Couldn't get file type for {:?}", entry.path());
1031 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1032 pub fn file_type(&self) -> io::Result<FileType> {
1033 self.0.file_type().map(FileType)
1036 /// Returns the bare file name of this directory entry without any other
1037 /// leading path component.
1044 /// if let Ok(entries) = fs::read_dir(".") {
1045 /// for entry in entries {
1046 /// if let Ok(entry) = entry {
1047 /// // Here, `entry` is a `DirEntry`.
1048 /// println!("{:?}", entry.file_name());
1053 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1054 pub fn file_name(&self) -> OsString {
1059 impl AsInner<fs_imp::DirEntry> for DirEntry {
1060 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
1063 /// Removes a file from the filesystem.
1065 /// Note that there is no
1066 /// guarantee that the file is immediately deleted (e.g. depending on
1067 /// platform, other open file descriptors may prevent immediate removal).
1069 /// # Platform-specific behavior
1071 /// This function currently corresponds to the `unlink` function on Unix
1072 /// and the `DeleteFile` function on Windows.
1073 /// Note that, this [may change in the future][changes].
1074 /// [changes]: ../io/index.html#platform-specific-behavior
1078 /// This function will return an error in the following situations, but is not
1079 /// limited to just these cases:
1081 /// * `path` points to a directory.
1082 /// * The user lacks permissions to remove the file.
1089 /// # fn foo() -> std::io::Result<()> {
1090 /// try!(fs::remove_file("a.txt"));
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1096 fs_imp::unlink(path.as_ref())
1099 /// Given a path, query the file system to get information about a file,
1102 /// This function will traverse symbolic links to query information about the
1103 /// destination file.
1105 /// # Platform-specific behavior
1107 /// This function currently corresponds to the `stat` function on Unix
1108 /// and the `GetFileAttributesEx` function on Windows.
1109 /// Note that, this [may change in the future][changes].
1110 /// [changes]: ../io/index.html#platform-specific-behavior
1114 /// This function will return an error in the following situations, but is not
1115 /// limited to just these cases:
1117 /// * The user lacks permissions to perform `metadata` call on `path`.
1118 /// * `path` does not exist.
1123 /// # fn foo() -> std::io::Result<()> {
1126 /// let attr = try!(fs::metadata("/some/file/path.txt"));
1127 /// // inspect attr ...
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1133 fs_imp::stat(path.as_ref()).map(Metadata)
1136 /// Query the metadata about a file without following symlinks.
1138 /// # Platform-specific behavior
1140 /// This function currently corresponds to the `lstat` function on Unix
1141 /// and the `GetFileAttributesEx` function on Windows.
1142 /// Note that, this [may change in the future][changes].
1143 /// [changes]: ../io/index.html#platform-specific-behavior
1147 /// This function will return an error in the following situations, but is not
1148 /// limited to just these cases:
1150 /// * The user lacks permissions to perform `metadata` call on `path`.
1151 /// * `path` does not exist.
1156 /// # fn foo() -> std::io::Result<()> {
1159 /// let attr = try!(fs::symlink_metadata("/some/file/path.txt"));
1160 /// // inspect attr ...
1164 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1165 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1166 fs_imp::lstat(path.as_ref()).map(Metadata)
1169 /// Rename a file or directory to a new name, replacing the original file if
1170 /// `to` already exists.
1172 /// This will not work if the new name is on a different mount point.
1174 /// # Platform-specific behavior
1176 /// This function currently corresponds to the `rename` function on Unix
1177 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1179 /// Because of this, the behavior when both `from` and `to` exist differs. On
1180 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1181 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1182 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1184 /// Note that, this [may change in the future][changes].
1185 /// [changes]: ../io/index.html#platform-specific-behavior
1189 /// This function will return an error in the following situations, but is not
1190 /// limited to just these cases:
1192 /// * `from` does not exist.
1193 /// * The user lacks permissions to view contents.
1194 /// * `from` and `to` are on separate filesystems.
1201 /// # fn foo() -> std::io::Result<()> {
1202 /// try!(fs::rename("a.txt", "b.txt")); // Rename a.txt to b.txt
1206 #[stable(feature = "rust1", since = "1.0.0")]
1207 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1208 fs_imp::rename(from.as_ref(), to.as_ref())
1211 /// Copies the contents of one file to another. This function will also
1212 /// copy the permission bits of the original file to the destination file.
1214 /// This function will **overwrite** the contents of `to`.
1216 /// Note that if `from` and `to` both point to the same file, then the file
1217 /// will likely get truncated by this operation.
1219 /// On success, the total number of bytes copied is returned.
1221 /// # Platform-specific behavior
1223 /// This function currently corresponds to the `open` function in Unix
1224 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1225 /// `O_CLOEXEC` is set for returned file descriptors.
1226 /// On Windows, this function currently corresponds to `CopyFileEx`.
1227 /// Note that, this [may change in the future][changes].
1228 /// [changes]: ../io/index.html#platform-specific-behavior
1232 /// This function will return an error in the following situations, but is not
1233 /// limited to just these cases:
1235 /// * The `from` path is not a file.
1236 /// * The `from` file does not exist.
1237 /// * The current process does not have the permission rights to access
1238 /// `from` or write `to`.
1245 /// # fn foo() -> std::io::Result<()> {
1246 /// try!(fs::copy("foo.txt", "bar.txt")); // Copy foo.txt to bar.txt
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1251 fs_imp::copy(from.as_ref(), to.as_ref())
1254 /// Creates a new hard link on the filesystem.
1256 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1257 /// often require these two paths to both be located on the same filesystem.
1259 /// # Platform-specific behavior
1261 /// This function currently corresponds to the `link` function on Unix
1262 /// and the `CreateHardLink` function on Windows.
1263 /// Note that, this [may change in the future][changes].
1264 /// [changes]: ../io/index.html#platform-specific-behavior
1268 /// This function will return an error in the following situations, but is not
1269 /// limited to just these cases:
1271 /// * The `src` path is not a file or doesn't exist.
1278 /// # fn foo() -> std::io::Result<()> {
1279 /// try!(fs::hard_link("a.txt", "b.txt")); // Hard link a.txt to b.txt
1283 #[stable(feature = "rust1", since = "1.0.0")]
1284 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1285 fs_imp::link(src.as_ref(), dst.as_ref())
1288 /// Creates a new symbolic link on the filesystem.
1290 /// The `dst` path will be a symbolic link pointing to the `src` path.
1291 /// On Windows, this will be a file symlink, not a directory symlink;
1292 /// for this reason, the platform-specific `std::os::unix::fs::symlink`
1293 /// and `std::os::windows::fs::{symlink_file, symlink_dir}` should be
1294 /// used instead to make the intent explicit.
1301 /// # fn foo() -> std::io::Result<()> {
1302 /// try!(fs::soft_link("a.txt", "b.txt"));
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 #[rustc_deprecated(since = "1.1.0",
1308 reason = "replaced with std::os::unix::fs::symlink and \
1309 std::os::windows::fs::{symlink_file, symlink_dir}")]
1310 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1311 fs_imp::symlink(src.as_ref(), dst.as_ref())
1314 /// Reads a symbolic link, returning the file that the link points to.
1316 /// # Platform-specific behavior
1318 /// This function currently corresponds to the `readlink` function on Unix
1319 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1320 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1321 /// Note that, this [may change in the future][changes].
1322 /// [changes]: ../io/index.html#platform-specific-behavior
1326 /// This function will return an error in the following situations, but is not
1327 /// limited to just these cases:
1329 /// * `path` is not a symbolic link.
1330 /// * `path` does not exist.
1337 /// # fn foo() -> std::io::Result<()> {
1338 /// let path = try!(fs::read_link("a.txt"));
1342 #[stable(feature = "rust1", since = "1.0.0")]
1343 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1344 fs_imp::readlink(path.as_ref())
1347 /// Returns the canonical form of a path with all intermediate components
1348 /// normalized and symbolic links resolved.
1350 /// # Platform-specific behavior
1352 /// This function currently corresponds to the `realpath` function on Unix
1353 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1354 /// Note that, this [may change in the future][changes].
1355 /// [changes]: ../io/index.html#platform-specific-behavior
1359 /// This function will return an error in the following situations, but is not
1360 /// limited to just these cases:
1362 /// * `path` does not exist.
1363 /// * A component in path is not a directory.
1370 /// # fn foo() -> std::io::Result<()> {
1371 /// let path = try!(fs::canonicalize("../a/../foo.txt"));
1375 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1376 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1377 fs_imp::canonicalize(path.as_ref())
1380 /// Creates a new, empty directory at the provided path
1382 /// # Platform-specific behavior
1384 /// This function currently corresponds to the `mkdir` function on Unix
1385 /// and the `CreateDirectory` function on Windows.
1386 /// Note that, this [may change in the future][changes].
1387 /// [changes]: ../io/index.html#platform-specific-behavior
1391 /// This function will return an error in the following situations, but is not
1392 /// limited to just these cases:
1394 /// * User lacks permissions to create directory at `path`.
1395 /// * `path` already exists.
1402 /// # fn foo() -> std::io::Result<()> {
1403 /// try!(fs::create_dir("/some/dir"));
1407 #[stable(feature = "rust1", since = "1.0.0")]
1408 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1409 DirBuilder::new().create(path.as_ref())
1412 /// Recursively create a directory and all of its parent components if they
1415 /// # Platform-specific behavior
1417 /// This function currently corresponds to the `mkdir` function on Unix
1418 /// and the `CreateDirectory` function on Windows.
1419 /// Note that, this [may change in the future][changes].
1420 /// [changes]: ../io/index.html#platform-specific-behavior
1424 /// This function will return an error in the following situations, but is not
1425 /// limited to just these cases:
1427 /// * If any directory in the path specified by `path`
1428 /// does not already exist and it could not be created otherwise. The specific
1429 /// error conditions for when a directory is being created (after it is
1430 /// determined to not exist) are outlined by `fs::create_dir`.
1437 /// # fn foo() -> std::io::Result<()> {
1438 /// try!(fs::create_dir_all("/some/dir"));
1442 #[stable(feature = "rust1", since = "1.0.0")]
1443 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1444 DirBuilder::new().recursive(true).create(path.as_ref())
1447 /// Removes an existing, empty directory.
1449 /// # Platform-specific behavior
1451 /// This function currently corresponds to the `rmdir` function on Unix
1452 /// and the `RemoveDirectory` function on Windows.
1453 /// Note that, this [may change in the future][changes].
1454 /// [changes]: ../io/index.html#platform-specific-behavior
1458 /// This function will return an error in the following situations, but is not
1459 /// limited to just these cases:
1461 /// * The user lacks permissions to remove the directory at the provided `path`.
1462 /// * The directory isn't empty.
1469 /// # fn foo() -> std::io::Result<()> {
1470 /// try!(fs::remove_dir("/some/dir"));
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1476 fs_imp::rmdir(path.as_ref())
1479 /// Removes a directory at this path, after removing all its contents. Use
1482 /// This function does **not** follow symbolic links and it will simply remove the
1483 /// symbolic link itself.
1485 /// # Platform-specific behavior
1487 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1488 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1490 /// Note that, this [may change in the future][changes].
1491 /// [changes]: ../io/index.html#platform-specific-behavior
1495 /// See `file::remove_file` and `fs::remove_dir`.
1502 /// # fn foo() -> std::io::Result<()> {
1503 /// try!(fs::remove_dir_all("/some/dir"));
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1509 fs_imp::remove_dir_all(path.as_ref())
1512 /// Returns an iterator over the entries within a directory.
1514 /// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
1515 /// be encountered after an iterator is initially constructed.
1517 /// # Platform-specific behavior
1519 /// This function currently corresponds to the `opendir` function on Unix
1520 /// and the `FindFirstFile` function on Windows.
1521 /// Note that, this [may change in the future][changes].
1522 /// [changes]: ../io/index.html#platform-specific-behavior
1526 /// This function will return an error in the following situations, but is not
1527 /// limited to just these cases:
1529 /// * The provided `path` doesn't exist.
1530 /// * The process lacks permissions to view the contents.
1531 /// * The `path` points at a non-directory file.
1537 /// use std::fs::{self, DirEntry};
1538 /// use std::path::Path;
1540 /// // one possible implementation of walking a directory only visiting files
1541 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1542 /// if dir.is_dir() {
1543 /// for entry in try!(fs::read_dir(dir)) {
1544 /// let entry = try!(entry);
1545 /// let path = entry.path();
1546 /// if path.is_dir() {
1547 /// try!(visit_dirs(&path, cb));
1556 #[stable(feature = "rust1", since = "1.0.0")]
1557 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1558 fs_imp::readdir(path.as_ref()).map(ReadDir)
1561 /// Changes the permissions found on a file or a directory.
1563 /// # Platform-specific behavior
1565 /// This function currently corresponds to the `chmod` function on Unix
1566 /// and the `SetFileAttributes` function on Windows.
1567 /// Note that, this [may change in the future][changes].
1568 /// [changes]: ../io/index.html#platform-specific-behavior
1572 /// This function will return an error in the following situations, but is not
1573 /// limited to just these cases:
1575 /// * `path` does not exist.
1576 /// * The user lacks the permission to change attributes of the file.
1581 /// # fn foo() -> std::io::Result<()> {
1584 /// let mut perms = try!(fs::metadata("foo.txt")).permissions();
1585 /// perms.set_readonly(true);
1586 /// try!(fs::set_permissions("foo.txt", perms));
1590 #[stable(feature = "set_permissions", since = "1.1.0")]
1591 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1593 fs_imp::set_perm(path.as_ref(), perm.0)
1597 /// Creates a new set of options with default mode/security settings for all
1598 /// platforms and also non-recursive.
1603 /// use std::fs::DirBuilder;
1605 /// let builder = DirBuilder::new();
1607 #[stable(feature = "dir_builder", since = "1.6.0")]
1608 pub fn new() -> DirBuilder {
1610 inner: fs_imp::DirBuilder::new(),
1615 /// Indicate that directories create should be created recursively, creating
1616 /// all parent directories if they do not exist with the same security and
1617 /// permissions settings.
1619 /// This option defaults to `false`.
1624 /// use std::fs::DirBuilder;
1626 /// let mut builder = DirBuilder::new();
1627 /// builder.recursive(true);
1629 #[stable(feature = "dir_builder", since = "1.6.0")]
1630 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
1631 self.recursive = recursive;
1635 /// Create the specified directory with the options configured in this
1641 /// use std::fs::{self, DirBuilder};
1643 /// let path = "/tmp/foo/bar/baz";
1644 /// DirBuilder::new()
1645 /// .recursive(true)
1646 /// .create(path).unwrap();
1648 /// assert!(fs::metadata(path).unwrap().is_dir());
1650 #[stable(feature = "dir_builder", since = "1.6.0")]
1651 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1652 self._create(path.as_ref())
1655 fn _create(&self, path: &Path) -> io::Result<()> {
1657 self.create_dir_all(path)
1659 self.inner.mkdir(path)
1663 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
1664 if path == Path::new("") || path.is_dir() { return Ok(()) }
1665 if let Some(p) = path.parent() {
1666 self.create_dir_all(p)?
1668 self.inner.mkdir(path)
1672 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
1673 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
1683 use fs::{self, File, OpenOptions};
1684 use io::{ErrorKind, SeekFrom};
1686 use rand::{StdRng, Rng};
1688 use sys_common::io::test::{TempDir, tmpdir};
1691 use os::windows::fs::{symlink_dir, symlink_file};
1693 use sys::fs::symlink_junction;
1695 use os::unix::fs::symlink as symlink_dir;
1697 use os::unix::fs::symlink as symlink_file;
1699 use os::unix::fs::symlink as symlink_junction;
1701 macro_rules! check { ($e:expr) => (
1704 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
1708 macro_rules! error { ($e:expr, $s:expr) => (
1710 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
1711 Err(ref err) => assert!(err.to_string().contains($s),
1712 format!("`{}` did not contain `{}`", err, $s))
1716 // Several test fail on windows if the user does not have permission to
1717 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
1718 // disabling these test on Windows, use this function to test whether we
1719 // have permission, and return otherwise. This way, we still don't run these
1720 // tests most of the time, but at least we do if the user has the right
1722 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
1723 if cfg!(unix) { return true }
1724 let link = tmpdir.join("some_hopefully_unique_link_name");
1726 match symlink_file(r"nonexisting_target", link) {
1729 if err.to_string().contains("A required privilege is not held by the client.") {
1738 fn file_test_io_smoke_test() {
1739 let message = "it's alright. have a good time";
1740 let tmpdir = tmpdir();
1741 let filename = &tmpdir.join("file_rt_io_file_test.txt");
1743 let mut write_stream = check!(File::create(filename));
1744 check!(write_stream.write(message.as_bytes()));
1747 let mut read_stream = check!(File::open(filename));
1748 let mut read_buf = [0; 1028];
1749 let read_str = match check!(read_stream.read(&mut read_buf)) {
1750 0 => panic!("shouldn't happen"),
1751 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
1753 assert_eq!(read_str, message);
1755 check!(fs::remove_file(filename));
1759 fn invalid_path_raises() {
1760 let tmpdir = tmpdir();
1761 let filename = &tmpdir.join("file_that_does_not_exist.txt");
1762 let result = File::open(filename);
1765 error!(result, "No such file or directory");
1768 error!(result, "The system cannot find the file specified");
1773 fn file_test_iounlinking_invalid_path_should_raise_condition() {
1774 let tmpdir = tmpdir();
1775 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
1777 let result = fs::remove_file(filename);
1780 error!(result, "No such file or directory");
1783 error!(result, "The system cannot find the file specified");
1788 fn file_test_io_non_positional_read() {
1789 let message: &str = "ten-four";
1790 let mut read_mem = [0; 8];
1791 let tmpdir = tmpdir();
1792 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
1794 let mut rw_stream = check!(File::create(filename));
1795 check!(rw_stream.write(message.as_bytes()));
1798 let mut read_stream = check!(File::open(filename));
1800 let read_buf = &mut read_mem[0..4];
1801 check!(read_stream.read(read_buf));
1804 let read_buf = &mut read_mem[4..8];
1805 check!(read_stream.read(read_buf));
1808 check!(fs::remove_file(filename));
1809 let read_str = str::from_utf8(&read_mem).unwrap();
1810 assert_eq!(read_str, message);
1814 fn file_test_io_seek_and_tell_smoke_test() {
1815 let message = "ten-four";
1816 let mut read_mem = [0; 4];
1817 let set_cursor = 4 as u64;
1818 let tell_pos_pre_read;
1819 let tell_pos_post_read;
1820 let tmpdir = tmpdir();
1821 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
1823 let mut rw_stream = check!(File::create(filename));
1824 check!(rw_stream.write(message.as_bytes()));
1827 let mut read_stream = check!(File::open(filename));
1828 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
1829 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
1830 check!(read_stream.read(&mut read_mem));
1831 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
1833 check!(fs::remove_file(filename));
1834 let read_str = str::from_utf8(&read_mem).unwrap();
1835 assert_eq!(read_str, &message[4..8]);
1836 assert_eq!(tell_pos_pre_read, set_cursor);
1837 assert_eq!(tell_pos_post_read, message.len() as u64);
1841 fn file_test_io_seek_and_write() {
1842 let initial_msg = "food-is-yummy";
1843 let overwrite_msg = "-the-bar!!";
1844 let final_msg = "foo-the-bar!!";
1846 let mut read_mem = [0; 13];
1847 let tmpdir = tmpdir();
1848 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
1850 let mut rw_stream = check!(File::create(filename));
1851 check!(rw_stream.write(initial_msg.as_bytes()));
1852 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
1853 check!(rw_stream.write(overwrite_msg.as_bytes()));
1856 let mut read_stream = check!(File::open(filename));
1857 check!(read_stream.read(&mut read_mem));
1859 check!(fs::remove_file(filename));
1860 let read_str = str::from_utf8(&read_mem).unwrap();
1861 assert!(read_str == final_msg);
1865 fn file_test_io_seek_shakedown() {
1867 let initial_msg = "qwer-asdf-zxcv";
1868 let chunk_one: &str = "qwer";
1869 let chunk_two: &str = "asdf";
1870 let chunk_three: &str = "zxcv";
1871 let mut read_mem = [0; 4];
1872 let tmpdir = tmpdir();
1873 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
1875 let mut rw_stream = check!(File::create(filename));
1876 check!(rw_stream.write(initial_msg.as_bytes()));
1879 let mut read_stream = check!(File::open(filename));
1881 check!(read_stream.seek(SeekFrom::End(-4)));
1882 check!(read_stream.read(&mut read_mem));
1883 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
1885 check!(read_stream.seek(SeekFrom::Current(-9)));
1886 check!(read_stream.read(&mut read_mem));
1887 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
1889 check!(read_stream.seek(SeekFrom::Start(0)));
1890 check!(read_stream.read(&mut read_mem));
1891 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
1893 check!(fs::remove_file(filename));
1897 fn file_test_stat_is_correct_on_is_file() {
1898 let tmpdir = tmpdir();
1899 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
1901 let mut opts = OpenOptions::new();
1902 let mut fs = check!(opts.read(true).write(true)
1903 .create(true).open(filename));
1905 fs.write(msg.as_bytes()).unwrap();
1907 let fstat_res = check!(fs.metadata());
1908 assert!(fstat_res.is_file());
1910 let stat_res_fn = check!(fs::metadata(filename));
1911 assert!(stat_res_fn.is_file());
1912 let stat_res_meth = check!(filename.metadata());
1913 assert!(stat_res_meth.is_file());
1914 check!(fs::remove_file(filename));
1918 fn file_test_stat_is_correct_on_is_dir() {
1919 let tmpdir = tmpdir();
1920 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
1921 check!(fs::create_dir(filename));
1922 let stat_res_fn = check!(fs::metadata(filename));
1923 assert!(stat_res_fn.is_dir());
1924 let stat_res_meth = check!(filename.metadata());
1925 assert!(stat_res_meth.is_dir());
1926 check!(fs::remove_dir(filename));
1930 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
1931 let tmpdir = tmpdir();
1932 let dir = &tmpdir.join("fileinfo_false_on_dir");
1933 check!(fs::create_dir(dir));
1934 assert!(!dir.is_file());
1935 check!(fs::remove_dir(dir));
1939 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
1940 let tmpdir = tmpdir();
1941 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
1942 check!(check!(File::create(file)).write(b"foo"));
1943 assert!(file.exists());
1944 check!(fs::remove_file(file));
1945 assert!(!file.exists());
1949 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
1950 let tmpdir = tmpdir();
1951 let dir = &tmpdir.join("before_and_after_dir");
1952 assert!(!dir.exists());
1953 check!(fs::create_dir(dir));
1954 assert!(dir.exists());
1955 assert!(dir.is_dir());
1956 check!(fs::remove_dir(dir));
1957 assert!(!dir.exists());
1961 fn file_test_directoryinfo_readdir() {
1962 let tmpdir = tmpdir();
1963 let dir = &tmpdir.join("di_readdir");
1964 check!(fs::create_dir(dir));
1967 let f = dir.join(&format!("{}.txt", n));
1968 let mut w = check!(File::create(&f));
1969 let msg_str = format!("{}{}", prefix, n.to_string());
1970 let msg = msg_str.as_bytes();
1971 check!(w.write(msg));
1973 let files = check!(fs::read_dir(dir));
1974 let mut mem = [0; 4];
1976 let f = f.unwrap().path();
1978 let n = f.file_stem().unwrap();
1979 check!(check!(File::open(&f)).read(&mut mem));
1980 let read_str = str::from_utf8(&mem).unwrap();
1981 let expected = format!("{}{}", prefix, n.to_str().unwrap());
1982 assert_eq!(expected, read_str);
1984 check!(fs::remove_file(&f));
1986 check!(fs::remove_dir(dir));
1990 fn file_create_new_already_exists_error() {
1991 let tmpdir = tmpdir();
1992 let file = &tmpdir.join("file_create_new_error_exists");
1993 check!(fs::File::create(file));
1994 let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
1995 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
1999 fn mkdir_path_already_exists_error() {
2000 let tmpdir = tmpdir();
2001 let dir = &tmpdir.join("mkdir_error_twice");
2002 check!(fs::create_dir(dir));
2003 let e = fs::create_dir(dir).unwrap_err();
2004 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2008 fn recursive_mkdir() {
2009 let tmpdir = tmpdir();
2010 let dir = tmpdir.join("d1/d2");
2011 check!(fs::create_dir_all(&dir));
2012 assert!(dir.is_dir())
2016 fn recursive_mkdir_failure() {
2017 let tmpdir = tmpdir();
2018 let dir = tmpdir.join("d1");
2019 let file = dir.join("f1");
2021 check!(fs::create_dir_all(&dir));
2022 check!(File::create(&file));
2024 let result = fs::create_dir_all(&file);
2026 assert!(result.is_err());
2030 fn recursive_mkdir_slash() {
2031 check!(fs::create_dir_all(&Path::new("/")));
2035 fn recursive_rmdir() {
2036 let tmpdir = tmpdir();
2037 let d1 = tmpdir.join("d1");
2038 let dt = d1.join("t");
2039 let dtt = dt.join("t");
2040 let d2 = tmpdir.join("d2");
2041 let canary = d2.join("do_not_delete");
2042 check!(fs::create_dir_all(&dtt));
2043 check!(fs::create_dir_all(&d2));
2044 check!(check!(File::create(&canary)).write(b"foo"));
2045 check!(symlink_junction(&d2, &dt.join("d2")));
2046 let _ = symlink_file(&canary, &d1.join("canary"));
2047 check!(fs::remove_dir_all(&d1));
2049 assert!(!d1.is_dir());
2050 assert!(canary.exists());
2054 fn recursive_rmdir_of_symlink() {
2055 // test we do not recursively delete a symlink but only dirs.
2056 let tmpdir = tmpdir();
2057 let link = tmpdir.join("d1");
2058 let dir = tmpdir.join("d2");
2059 let canary = dir.join("do_not_delete");
2060 check!(fs::create_dir_all(&dir));
2061 check!(check!(File::create(&canary)).write(b"foo"));
2062 check!(symlink_junction(&dir, &link));
2063 check!(fs::remove_dir_all(&link));
2065 assert!(!link.is_dir());
2066 assert!(canary.exists());
2070 // only Windows makes a distinction between file and directory symlinks.
2072 fn recursive_rmdir_of_file_symlink() {
2073 let tmpdir = tmpdir();
2074 if !got_symlink_permission(&tmpdir) { return };
2076 let f1 = tmpdir.join("f1");
2077 let f2 = tmpdir.join("f2");
2078 check!(check!(File::create(&f1)).write(b"foo"));
2079 check!(symlink_file(&f1, &f2));
2080 match fs::remove_dir_all(&f2) {
2081 Ok(..) => panic!("wanted a failure"),
2087 fn unicode_path_is_dir() {
2088 assert!(Path::new(".").is_dir());
2089 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2091 let tmpdir = tmpdir();
2093 let mut dirpath = tmpdir.path().to_path_buf();
2094 dirpath.push("test-가一ー你好");
2095 check!(fs::create_dir(&dirpath));
2096 assert!(dirpath.is_dir());
2098 let mut filepath = dirpath;
2099 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2100 check!(File::create(&filepath)); // ignore return; touch only
2101 assert!(!filepath.is_dir());
2102 assert!(filepath.exists());
2106 fn unicode_path_exists() {
2107 assert!(Path::new(".").exists());
2108 assert!(!Path::new("test/nonexistent-bogus-path").exists());
2110 let tmpdir = tmpdir();
2111 let unicode = tmpdir.path();
2112 let unicode = unicode.join(&format!("test-각丁ー再见"));
2113 check!(fs::create_dir(&unicode));
2114 assert!(unicode.exists());
2115 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2119 fn copy_file_does_not_exist() {
2120 let from = Path::new("test/nonexistent-bogus-path");
2121 let to = Path::new("test/other-bogus-path");
2123 match fs::copy(&from, &to) {
2126 assert!(!from.exists());
2127 assert!(!to.exists());
2133 fn copy_src_does_not_exist() {
2134 let tmpdir = tmpdir();
2135 let from = Path::new("test/nonexistent-bogus-path");
2136 let to = tmpdir.join("out.txt");
2137 check!(check!(File::create(&to)).write(b"hello"));
2138 assert!(fs::copy(&from, &to).is_err());
2139 assert!(!from.exists());
2140 let mut v = Vec::new();
2141 check!(check!(File::open(&to)).read_to_end(&mut v));
2142 assert_eq!(v, b"hello");
2147 let tmpdir = tmpdir();
2148 let input = tmpdir.join("in.txt");
2149 let out = tmpdir.join("out.txt");
2151 check!(check!(File::create(&input)).write(b"hello"));
2152 check!(fs::copy(&input, &out));
2153 let mut v = Vec::new();
2154 check!(check!(File::open(&out)).read_to_end(&mut v));
2155 assert_eq!(v, b"hello");
2157 assert_eq!(check!(input.metadata()).permissions(),
2158 check!(out.metadata()).permissions());
2162 fn copy_file_dst_dir() {
2163 let tmpdir = tmpdir();
2164 let out = tmpdir.join("out");
2166 check!(File::create(&out));
2167 match fs::copy(&*out, tmpdir.path()) {
2168 Ok(..) => panic!(), Err(..) => {}
2173 fn copy_file_dst_exists() {
2174 let tmpdir = tmpdir();
2175 let input = tmpdir.join("in");
2176 let output = tmpdir.join("out");
2178 check!(check!(File::create(&input)).write("foo".as_bytes()));
2179 check!(check!(File::create(&output)).write("bar".as_bytes()));
2180 check!(fs::copy(&input, &output));
2182 let mut v = Vec::new();
2183 check!(check!(File::open(&output)).read_to_end(&mut v));
2184 assert_eq!(v, b"foo".to_vec());
2188 fn copy_file_src_dir() {
2189 let tmpdir = tmpdir();
2190 let out = tmpdir.join("out");
2192 match fs::copy(tmpdir.path(), &out) {
2193 Ok(..) => panic!(), Err(..) => {}
2195 assert!(!out.exists());
2199 fn copy_file_preserves_perm_bits() {
2200 let tmpdir = tmpdir();
2201 let input = tmpdir.join("in.txt");
2202 let out = tmpdir.join("out.txt");
2204 let attr = check!(check!(File::create(&input)).metadata());
2205 let mut p = attr.permissions();
2206 p.set_readonly(true);
2207 check!(fs::set_permissions(&input, p));
2208 check!(fs::copy(&input, &out));
2209 assert!(check!(out.metadata()).permissions().readonly());
2210 check!(fs::set_permissions(&input, attr.permissions()));
2211 check!(fs::set_permissions(&out, attr.permissions()));
2216 fn copy_file_preserves_streams() {
2218 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2219 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 6);
2220 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2221 let mut v = Vec::new();
2222 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2223 assert_eq!(v, b"carrot".to_vec());
2227 fn symlinks_work() {
2228 let tmpdir = tmpdir();
2229 if !got_symlink_permission(&tmpdir) { return };
2231 let input = tmpdir.join("in.txt");
2232 let out = tmpdir.join("out.txt");
2234 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2235 check!(symlink_file(&input, &out));
2236 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
2237 assert_eq!(check!(fs::metadata(&out)).len(),
2238 check!(fs::metadata(&input)).len());
2239 let mut v = Vec::new();
2240 check!(check!(File::open(&out)).read_to_end(&mut v));
2241 assert_eq!(v, b"foobar".to_vec());
2245 fn symlink_noexist() {
2246 // Symlinks can point to things that don't exist
2247 let tmpdir = tmpdir();
2248 if !got_symlink_permission(&tmpdir) { return };
2250 // Use a relative path for testing. Symlinks get normalized by Windows,
2251 // so we may not get the same path back for absolute paths
2252 check!(symlink_file(&"foo", &tmpdir.join("bar")));
2253 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(),
2260 // directory symlink
2261 assert_eq!(check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
2264 assert_eq!(check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
2265 r"C:\Users\Default");
2266 // junction with special permissions
2267 assert_eq!(check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
2270 let tmpdir = tmpdir();
2271 let link = tmpdir.join("link");
2272 if !got_symlink_permission(&tmpdir) { return };
2273 check!(symlink_file(&"foo", &link));
2274 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
2278 fn readlink_not_symlink() {
2279 let tmpdir = tmpdir();
2280 match fs::read_link(tmpdir.path()) {
2281 Ok(..) => panic!("wanted a failure"),
2288 let tmpdir = tmpdir();
2289 let input = tmpdir.join("in.txt");
2290 let out = tmpdir.join("out.txt");
2292 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2293 check!(fs::hard_link(&input, &out));
2294 assert_eq!(check!(fs::metadata(&out)).len(),
2295 check!(fs::metadata(&input)).len());
2296 assert_eq!(check!(fs::metadata(&out)).len(),
2297 check!(input.metadata()).len());
2298 let mut v = Vec::new();
2299 check!(check!(File::open(&out)).read_to_end(&mut v));
2300 assert_eq!(v, b"foobar".to_vec());
2302 // can't link to yourself
2303 match fs::hard_link(&input, &input) {
2304 Ok(..) => panic!("wanted a failure"),
2307 // can't link to something that doesn't exist
2308 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
2309 Ok(..) => panic!("wanted a failure"),
2316 let tmpdir = tmpdir();
2317 let file = tmpdir.join("in.txt");
2319 check!(File::create(&file));
2320 let attr = check!(fs::metadata(&file));
2321 assert!(!attr.permissions().readonly());
2322 let mut p = attr.permissions();
2323 p.set_readonly(true);
2324 check!(fs::set_permissions(&file, p.clone()));
2325 let attr = check!(fs::metadata(&file));
2326 assert!(attr.permissions().readonly());
2328 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
2329 Ok(..) => panic!("wanted an error"),
2333 p.set_readonly(false);
2334 check!(fs::set_permissions(&file, p));
2338 fn sync_doesnt_kill_anything() {
2339 let tmpdir = tmpdir();
2340 let path = tmpdir.join("in.txt");
2342 let mut file = check!(File::create(&path));
2343 check!(file.sync_all());
2344 check!(file.sync_data());
2345 check!(file.write(b"foo"));
2346 check!(file.sync_all());
2347 check!(file.sync_data());
2351 fn truncate_works() {
2352 let tmpdir = tmpdir();
2353 let path = tmpdir.join("in.txt");
2355 let mut file = check!(File::create(&path));
2356 check!(file.write(b"foo"));
2357 check!(file.sync_all());
2359 // Do some simple things with truncation
2360 assert_eq!(check!(file.metadata()).len(), 3);
2361 check!(file.set_len(10));
2362 assert_eq!(check!(file.metadata()).len(), 10);
2363 check!(file.write(b"bar"));
2364 check!(file.sync_all());
2365 assert_eq!(check!(file.metadata()).len(), 10);
2367 let mut v = Vec::new();
2368 check!(check!(File::open(&path)).read_to_end(&mut v));
2369 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
2371 // Truncate to a smaller length, don't seek, and then write something.
2372 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
2373 // past the end of the file).
2374 check!(file.set_len(2));
2375 assert_eq!(check!(file.metadata()).len(), 2);
2376 check!(file.write(b"wut"));
2377 check!(file.sync_all());
2378 assert_eq!(check!(file.metadata()).len(), 9);
2379 let mut v = Vec::new();
2380 check!(check!(File::open(&path)).read_to_end(&mut v));
2381 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
2386 use fs::OpenOptions as OO;
2387 fn c<T: Clone>(t: &T) -> T { t.clone() }
2389 let tmpdir = tmpdir();
2391 let mut r = OO::new(); r.read(true);
2392 let mut w = OO::new(); w.write(true);
2393 let mut rw = OO::new(); rw.read(true).write(true);
2394 let mut a = OO::new(); a.append(true);
2395 let mut ra = OO::new(); ra.read(true).append(true);
2397 let invalid_options = if cfg!(windows) { "The parameter is incorrect" }
2398 else { "Invalid argument" };
2400 // Test various combinations of creation modes and access modes.
2403 // creation mode | read | write | read-write | append | read-append |
2404 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
2405 // not set (open existing) | X | X | X | X | X |
2406 // create | | X | X | X | X |
2407 // truncate | | X | X | | |
2408 // create and truncate | | X | X | | |
2409 // create_new | | X | X | X | X |
2411 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
2414 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
2415 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
2416 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
2417 check!(c(&w).create(true).open(&tmpdir.join("a")));
2418 check!(c(&w).open(&tmpdir.join("a")));
2421 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
2422 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
2423 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
2424 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
2425 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
2428 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
2429 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
2430 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
2431 check!(c(&rw).create(true).open(&tmpdir.join("c")));
2432 check!(c(&rw).open(&tmpdir.join("c")));
2435 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
2436 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
2437 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
2438 check!(c(&a).create(true).open(&tmpdir.join("d")));
2439 check!(c(&a).open(&tmpdir.join("d")));
2442 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
2443 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
2444 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
2445 check!(c(&ra).create(true).open(&tmpdir.join("e")));
2446 check!(c(&ra).open(&tmpdir.join("e")));
2448 // Test opening a file without setting an access mode
2449 let mut blank = OO::new();
2450 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
2453 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
2455 // Test write fails for read-only
2456 check!(r.open(&tmpdir.join("h")));
2458 let mut f = check!(r.open(&tmpdir.join("h")));
2459 assert!(f.write("wut".as_bytes()).is_err());
2462 // Test write overwrites
2464 let mut f = check!(c(&w).open(&tmpdir.join("h")));
2465 check!(f.write("baz".as_bytes()));
2468 let mut f = check!(c(&r).open(&tmpdir.join("h")));
2469 let mut b = vec![0; 6];
2470 check!(f.read(&mut b));
2471 assert_eq!(b, "bazbar".as_bytes());
2474 // Test truncate works
2476 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
2477 check!(f.write("foo".as_bytes()));
2479 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2481 // Test append works
2482 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
2484 let mut f = check!(c(&a).open(&tmpdir.join("h")));
2485 check!(f.write("bar".as_bytes()));
2487 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
2489 // Test .append(true) equals .write(true).append(true)
2491 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
2492 check!(f.write("baz".as_bytes()));
2494 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
2498 fn _assert_send_sync() {
2499 fn _assert_send_sync<T: Send + Sync>() {}
2500 _assert_send_sync::<OpenOptions>();
2505 let mut bytes = [0; 1024];
2506 StdRng::new().unwrap().fill_bytes(&mut bytes);
2508 let tmpdir = tmpdir();
2510 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
2511 let mut v = Vec::new();
2512 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
2513 assert!(v == &bytes[..]);
2517 fn file_try_clone() {
2518 let tmpdir = tmpdir();
2520 let mut f1 = check!(OpenOptions::new()
2524 .open(&tmpdir.join("test")));
2525 let mut f2 = check!(f1.try_clone());
2527 check!(f1.write_all(b"hello world"));
2528 check!(f1.seek(SeekFrom::Start(2)));
2530 let mut buf = vec![];
2531 check!(f2.read_to_end(&mut buf));
2532 assert_eq!(buf, b"llo world");
2535 check!(f1.write_all(b"!"));
2539 #[cfg(not(windows))]
2540 fn unlink_readonly() {
2541 let tmpdir = tmpdir();
2542 let path = tmpdir.join("file");
2543 check!(File::create(&path));
2544 let mut perm = check!(fs::metadata(&path)).permissions();
2545 perm.set_readonly(true);
2546 check!(fs::set_permissions(&path, perm));
2547 check!(fs::remove_file(&path));
2551 fn mkdir_trailing_slash() {
2552 let tmpdir = tmpdir();
2553 let path = tmpdir.join("file");
2554 check!(fs::create_dir_all(&path.join("a/")));
2558 fn canonicalize_works_simple() {
2559 let tmpdir = tmpdir();
2560 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2561 let file = tmpdir.join("test");
2562 File::create(&file).unwrap();
2563 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2567 fn realpath_works() {
2568 let tmpdir = tmpdir();
2569 if !got_symlink_permission(&tmpdir) { return };
2571 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2572 let file = tmpdir.join("test");
2573 let dir = tmpdir.join("test2");
2574 let link = dir.join("link");
2575 let linkdir = tmpdir.join("test3");
2577 File::create(&file).unwrap();
2578 fs::create_dir(&dir).unwrap();
2579 symlink_file(&file, &link).unwrap();
2580 symlink_dir(&dir, &linkdir).unwrap();
2582 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
2584 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
2585 assert_eq!(fs::canonicalize(&file).unwrap(), file);
2586 assert_eq!(fs::canonicalize(&link).unwrap(), file);
2587 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
2588 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
2592 fn realpath_works_tricky() {
2593 let tmpdir = tmpdir();
2594 if !got_symlink_permission(&tmpdir) { return };
2596 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
2597 let a = tmpdir.join("a");
2598 let b = a.join("b");
2599 let c = b.join("c");
2600 let d = a.join("d");
2601 let e = d.join("e");
2602 let f = a.join("f");
2604 fs::create_dir_all(&b).unwrap();
2605 fs::create_dir_all(&d).unwrap();
2606 File::create(&f).unwrap();
2607 if cfg!(not(windows)) {
2608 symlink_dir("../d/e", &c).unwrap();
2609 symlink_file("../f", &e).unwrap();
2612 symlink_dir(r"..\d\e", &c).unwrap();
2613 symlink_file(r"..\f", &e).unwrap();
2616 assert_eq!(fs::canonicalize(&c).unwrap(), f);
2617 assert_eq!(fs::canonicalize(&e).unwrap(), f);
2621 fn dir_entry_methods() {
2622 let tmpdir = tmpdir();
2624 fs::create_dir_all(&tmpdir.join("a")).unwrap();
2625 File::create(&tmpdir.join("b")).unwrap();
2627 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
2628 let fname = file.file_name();
2629 match fname.to_str() {
2631 assert!(file.file_type().unwrap().is_dir());
2632 assert!(file.metadata().unwrap().is_dir());
2635 assert!(file.file_type().unwrap().is_file());
2636 assert!(file.metadata().unwrap().is_file());
2638 f => panic!("unknown file name: {:?}", f),
2644 fn read_dir_not_found() {
2645 let res = fs::read_dir("/path/that/does/not/exist");
2646 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
2650 fn create_dir_all_with_junctions() {
2651 let tmpdir = tmpdir();
2652 let target = tmpdir.join("target");
2654 let junction = tmpdir.join("junction");
2655 let b = junction.join("a/b");
2657 let link = tmpdir.join("link");
2658 let d = link.join("c/d");
2660 fs::create_dir(&target).unwrap();
2662 check!(symlink_junction(&target, &junction));
2663 check!(fs::create_dir_all(&b));
2664 // the junction itself is not a directory, but `is_dir()` on a Path
2666 assert!(junction.is_dir());
2667 assert!(b.exists());
2669 if !got_symlink_permission(&tmpdir) { return };
2670 check!(symlink_dir(&target, &link));
2671 check!(fs::create_dir_all(&d));
2672 assert!(link.is_dir());
2673 assert!(d.exists());
2677 fn metadata_access_times() {
2678 let tmpdir = tmpdir();
2680 let b = tmpdir.join("b");
2681 File::create(&b).unwrap();
2683 let a = check!(fs::metadata(&tmpdir.path()));
2684 let b = check!(fs::metadata(&b));
2686 assert_eq!(check!(a.accessed()), check!(a.accessed()));
2687 assert_eq!(check!(a.modified()), check!(a.modified()));
2688 assert_eq!(check!(b.accessed()), check!(b.modified()));
2690 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
2691 check!(a.created());
2692 check!(b.created());