1 //! Filesystem manipulation operations.
3 //! This module contains basic methods to manipulate the contents of the local
4 //! filesystem. All methods in this module represent cross-platform filesystem
5 //! operations. Extra platform-specific functionality can be found in the
6 //! extension traits of `std::os::$platform`.
8 #![stable(feature = "rust1", since = "1.0.0")]
12 use io::{self, SeekFrom, Seek, Read, Initializer, Write};
13 use path::{Path, PathBuf};
14 use sys::fs as fs_imp;
15 use sys_common::{AsInnerMut, FromInner, AsInner, IntoInner};
18 /// A reference to an open file on the filesystem.
20 /// An instance of a `File` can be read and/or written depending on what options
21 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
22 /// that the file contains internally.
24 /// Files are automatically closed when they go out of scope.
28 /// Create a new file and write bytes to it:
31 /// use std::fs::File;
32 /// use std::io::prelude::*;
34 /// fn main() -> std::io::Result<()> {
35 /// let mut file = File::create("foo.txt")?;
36 /// file.write_all(b"Hello, world!")?;
41 /// Read the contents of a file into a [`String`]:
44 /// use std::fs::File;
45 /// use std::io::prelude::*;
47 /// fn main() -> std::io::Result<()> {
48 /// let mut file = File::open("foo.txt")?;
49 /// let mut contents = String::new();
50 /// file.read_to_string(&mut contents)?;
51 /// assert_eq!(contents, "Hello, world!");
56 /// It can be more efficient to read the contents of a file with a buffered
57 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
60 /// use std::fs::File;
61 /// use std::io::BufReader;
62 /// use std::io::prelude::*;
64 /// fn main() -> std::io::Result<()> {
65 /// let file = File::open("foo.txt")?;
66 /// let mut buf_reader = BufReader::new(file);
67 /// let mut contents = String::new();
68 /// buf_reader.read_to_string(&mut contents)?;
69 /// assert_eq!(contents, "Hello, world!");
74 /// Note that, although read and write methods require a `&mut File`, because
75 /// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
76 /// still modify the file, either through methods that take `&File` or by
77 /// retrieving the underlying OS object and modifying the file that way.
78 /// Additionally, many operating systems allow concurrent modification of files
79 /// by different processes. Avoid assuming that holding a `&File` means that the
80 /// file will not change.
82 /// [`Seek`]: ../io/trait.Seek.html
83 /// [`String`]: ../string/struct.String.html
84 /// [`Read`]: ../io/trait.Read.html
85 /// [`Write`]: ../io/trait.Write.html
86 /// [`BufReader<R>`]: ../io/struct.BufReader.html
87 #[stable(feature = "rust1", since = "1.0.0")]
92 /// Metadata information about a file.
94 /// This structure is returned from the [`metadata`] or
95 /// [`symlink_metadata`] function or method and represents known
96 /// metadata about a file such as its permissions, size, modification
99 /// [`metadata`]: fn.metadata.html
100 /// [`symlink_metadata`]: fn.symlink_metadata.html
101 #[stable(feature = "rust1", since = "1.0.0")]
103 pub struct Metadata(fs_imp::FileAttr);
105 /// Iterator over the entries in a directory.
107 /// This iterator is returned from the [`read_dir`] function of this module and
108 /// will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. Through a [`DirEntry`]
109 /// information like the entry's path and possibly other metadata can be
114 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
115 /// IO error during iteration.
117 /// [`read_dir`]: fn.read_dir.html
118 /// [`DirEntry`]: struct.DirEntry.html
119 /// [`io::Result`]: ../io/type.Result.html
120 /// [`Err`]: ../result/enum.Result.html#variant.Err
121 #[stable(feature = "rust1", since = "1.0.0")]
123 pub struct ReadDir(fs_imp::ReadDir);
125 /// Entries returned by the [`ReadDir`] iterator.
127 /// [`ReadDir`]: struct.ReadDir.html
129 /// An instance of `DirEntry` represents an entry inside of a directory on the
130 /// filesystem. Each entry can be inspected via methods to learn about the full
131 /// path or possibly other metadata through per-platform extension traits.
132 #[stable(feature = "rust1", since = "1.0.0")]
133 pub struct DirEntry(fs_imp::DirEntry);
135 /// Options and flags which can be used to configure how a file is opened.
137 /// This builder exposes the ability to configure how a [`File`] is opened and
138 /// what operations are permitted on the open file. The [`File::open`] and
139 /// [`File::create`] methods are aliases for commonly used options using this
142 /// [`File`]: struct.File.html
143 /// [`File::open`]: struct.File.html#method.open
144 /// [`File::create`]: struct.File.html#method.create
146 /// Generally speaking, when using `OpenOptions`, you'll first call [`new`],
147 /// then chain calls to methods to set each option, then call [`open`],
148 /// passing the path of the file you're trying to open. This will give you a
149 /// [`io::Result`][result] with a [`File`][file] inside that you can further
152 /// [`new`]: struct.OpenOptions.html#method.new
153 /// [`open`]: struct.OpenOptions.html#method.open
154 /// [result]: ../io/type.Result.html
155 /// [file]: struct.File.html
159 /// Opening a file to read:
162 /// use std::fs::OpenOptions;
164 /// let file = OpenOptions::new().read(true).open("foo.txt");
167 /// Opening a file for both reading and writing, as well as creating it if it
171 /// use std::fs::OpenOptions;
173 /// let file = OpenOptions::new()
177 /// .open("foo.txt");
179 #[derive(Clone, Debug)]
180 #[stable(feature = "rust1", since = "1.0.0")]
181 pub struct OpenOptions(fs_imp::OpenOptions);
183 /// Representation of the various permissions on a file.
185 /// This module only currently provides one bit of information, [`readonly`],
186 /// which is exposed on all currently supported platforms. Unix-specific
187 /// functionality, such as mode bits, is available through the
188 /// [`PermissionsExt`] trait.
190 /// [`readonly`]: struct.Permissions.html#method.readonly
191 /// [`PermissionsExt`]: ../os/unix/fs/trait.PermissionsExt.html
192 #[derive(Clone, PartialEq, Eq, Debug)]
193 #[stable(feature = "rust1", since = "1.0.0")]
194 pub struct Permissions(fs_imp::FilePermissions);
196 /// A structure representing a type of file with accessors for each file type.
197 /// It is returned by [`Metadata::file_type`] method.
199 /// [`Metadata::file_type`]: struct.Metadata.html#method.file_type
200 #[stable(feature = "file_type", since = "1.1.0")]
201 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
202 pub struct FileType(fs_imp::FileType);
204 /// A builder used to create directories in various manners.
206 /// This builder also supports platform-specific options.
207 #[stable(feature = "dir_builder", since = "1.6.0")]
209 pub struct DirBuilder {
210 inner: fs_imp::DirBuilder,
214 /// How large a buffer to pre-allocate before reading the entire file.
215 fn initial_buffer_size(file: &File) -> usize {
216 // Allocate one extra byte so the buffer doesn't need to grow before the
217 // final `read` call at the end of the file. Don't worry about `usize`
218 // overflow because reading will fail regardless in that case.
219 file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
222 /// Read the entire contents of a file into a bytes vector.
224 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
225 /// with fewer imports and without an intermediate variable. It pre-allocates a
226 /// buffer based on the file size when available, so it is generally faster than
227 /// reading into a vector created with `Vec::new()`.
229 /// [`File::open`]: struct.File.html#method.open
230 /// [`read_to_end`]: ../io/trait.Read.html#method.read_to_end
234 /// This function will return an error if `path` does not already exist.
235 /// Other errors may also be returned according to [`OpenOptions::open`].
237 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
239 /// It will also return an error if it encounters while reading an error
240 /// of a kind other than [`ErrorKind::Interrupted`].
242 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
248 /// use std::net::SocketAddr;
250 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
251 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
255 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
256 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
257 let mut file = File::open(path)?;
258 let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
259 file.read_to_end(&mut bytes)?;
263 /// Read the entire contents of a file into a string.
265 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
266 /// with fewer imports and without an intermediate variable. It pre-allocates a
267 /// buffer based on the file size when available, so it is generally faster than
268 /// reading into a string created with `String::new()`.
270 /// [`File::open`]: struct.File.html#method.open
271 /// [`read_to_string`]: ../io/trait.Read.html#method.read_to_string
275 /// This function will return an error if `path` does not already exist.
276 /// Other errors may also be returned according to [`OpenOptions::open`].
278 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
280 /// It will also return an error if it encounters while reading an error
281 /// of a kind other than [`ErrorKind::Interrupted`],
282 /// or if the contents of the file are not valid UTF-8.
284 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
290 /// use std::net::SocketAddr;
292 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
293 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
297 #[stable(feature = "fs_read_write", since = "1.26.0")]
298 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
299 let mut file = File::open(path)?;
300 let mut string = String::with_capacity(initial_buffer_size(&file));
301 file.read_to_string(&mut string)?;
305 /// Write a slice as the entire contents of a file.
307 /// This function will create a file if it does not exist,
308 /// and will entirely replace its contents if it does.
310 /// This is a convenience function for using [`File::create`] and [`write_all`]
311 /// with fewer imports.
313 /// [`File::create`]: struct.File.html#method.create
314 /// [`write_all`]: ../io/trait.Write.html#method.write_all
321 /// fn main() -> std::io::Result<()> {
322 /// fs::write("foo.txt", b"Lorem ipsum")?;
323 /// fs::write("bar.txt", "dolor sit")?;
327 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
328 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
329 File::create(path)?.write_all(contents.as_ref())
333 /// Attempts to open a file in read-only mode.
335 /// See the [`OpenOptions::open`] method for more details.
339 /// This function will return an error if `path` does not already exist.
340 /// Other errors may also be returned according to [`OpenOptions::open`].
342 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
347 /// use std::fs::File;
349 /// fn main() -> std::io::Result<()> {
350 /// let mut f = File::open("foo.txt")?;
354 #[stable(feature = "rust1", since = "1.0.0")]
355 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
356 OpenOptions::new().read(true).open(path.as_ref())
359 /// Opens a file in write-only mode.
361 /// This function will create a file if it does not exist,
362 /// and will truncate it if it does.
364 /// See the [`OpenOptions::open`] function for more details.
366 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
371 /// use std::fs::File;
373 /// fn main() -> std::io::Result<()> {
374 /// let mut f = File::create("foo.txt")?;
378 #[stable(feature = "rust1", since = "1.0.0")]
379 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
380 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
383 /// Attempts to sync all OS-internal metadata to disk.
385 /// This function will attempt to ensure that all in-core data reaches the
386 /// filesystem before returning.
391 /// use std::fs::File;
392 /// use std::io::prelude::*;
394 /// fn main() -> std::io::Result<()> {
395 /// let mut f = File::create("foo.txt")?;
396 /// f.write_all(b"Hello, world!")?;
402 #[stable(feature = "rust1", since = "1.0.0")]
403 pub fn sync_all(&self) -> io::Result<()> {
407 /// This function is similar to [`sync_all`], except that it may not
408 /// synchronize file metadata to the filesystem.
410 /// This is intended for use cases that must synchronize content, but don't
411 /// need the metadata on disk. The goal of this method is to reduce disk
414 /// Note that some platforms may simply implement this in terms of
417 /// [`sync_all`]: struct.File.html#method.sync_all
422 /// use std::fs::File;
423 /// use std::io::prelude::*;
425 /// fn main() -> std::io::Result<()> {
426 /// let mut f = File::create("foo.txt")?;
427 /// f.write_all(b"Hello, world!")?;
433 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn sync_data(&self) -> io::Result<()> {
435 self.inner.datasync()
438 /// Truncates or extends the underlying file, updating the size of
439 /// this file to become `size`.
441 /// If the `size` is less than the current file's size, then the file will
442 /// be shrunk. If it is greater than the current file's size, then the file
443 /// will be extended to `size` and have all of the intermediate data filled
446 /// The file's cursor isn't changed. In particular, if the cursor was at the
447 /// end and the file is shrunk using this operation, the cursor will now be
452 /// This function will return an error if the file is not opened for writing.
457 /// use std::fs::File;
459 /// fn main() -> std::io::Result<()> {
460 /// let mut f = File::create("foo.txt")?;
466 /// Note that this method alters the content of the underlying file, even
467 /// though it takes `&self` rather than `&mut self`.
468 #[stable(feature = "rust1", since = "1.0.0")]
469 pub fn set_len(&self, size: u64) -> io::Result<()> {
470 self.inner.truncate(size)
473 /// Queries metadata about the underlying file.
478 /// use std::fs::File;
480 /// fn main() -> std::io::Result<()> {
481 /// let mut f = File::open("foo.txt")?;
482 /// let metadata = f.metadata()?;
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub fn metadata(&self) -> io::Result<Metadata> {
488 self.inner.file_attr().map(Metadata)
491 /// Create a new `File` instance that shares the same underlying file handle
492 /// as the existing `File` instance. Reads, writes, and seeks will affect
493 /// both `File` instances simultaneously.
497 /// Create two handles for a file named `foo.txt`:
500 /// use std::fs::File;
502 /// fn main() -> std::io::Result<()> {
503 /// let mut file = File::open("foo.txt")?;
504 /// let file_copy = file.try_clone()?;
509 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
510 /// two handles, seek one of them, and read the remaining bytes from the
514 /// use std::fs::File;
515 /// use std::io::SeekFrom;
516 /// use std::io::prelude::*;
518 /// fn main() -> std::io::Result<()> {
519 /// let mut file = File::open("foo.txt")?;
520 /// let mut file_copy = file.try_clone()?;
522 /// file.seek(SeekFrom::Start(3))?;
524 /// let mut contents = vec![];
525 /// file_copy.read_to_end(&mut contents)?;
526 /// assert_eq!(contents, b"def\n");
530 #[stable(feature = "file_try_clone", since = "1.9.0")]
531 pub fn try_clone(&self) -> io::Result<File> {
533 inner: self.inner.duplicate()?
537 /// Changes the permissions on the underlying file.
539 /// # Platform-specific behavior
541 /// This function currently corresponds to the `fchmod` function on Unix and
542 /// the `SetFileInformationByHandle` function on Windows. Note that, this
543 /// [may change in the future][changes].
545 /// [changes]: ../io/index.html#platform-specific-behavior
549 /// This function will return an error if the user lacks permission change
550 /// attributes on the underlying file. It may also return an error in other
551 /// os-specific unspecified cases.
556 /// fn main() -> std::io::Result<()> {
557 /// use std::fs::File;
559 /// let file = File::open("foo.txt")?;
560 /// let mut perms = file.metadata()?.permissions();
561 /// perms.set_readonly(true);
562 /// file.set_permissions(perms)?;
567 /// Note that this method alters the permissions of the underlying file,
568 /// even though it takes `&self` rather than `&mut self`.
569 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
570 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
571 self.inner.set_permissions(perm.0)
575 impl AsInner<fs_imp::File> for File {
576 fn as_inner(&self) -> &fs_imp::File { &self.inner }
578 impl FromInner<fs_imp::File> for File {
579 fn from_inner(f: fs_imp::File) -> File {
583 impl IntoInner<fs_imp::File> for File {
584 fn into_inner(self) -> fs_imp::File {
589 #[stable(feature = "rust1", since = "1.0.0")]
590 impl fmt::Debug for File {
591 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
596 #[stable(feature = "rust1", since = "1.0.0")]
598 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
603 unsafe fn initializer(&self) -> Initializer {
607 #[stable(feature = "rust1", since = "1.0.0")]
608 impl Write for File {
609 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
610 self.inner.write(buf)
612 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
614 #[stable(feature = "rust1", since = "1.0.0")]
616 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
620 #[stable(feature = "rust1", since = "1.0.0")]
621 impl<'a> Read for &'a File {
622 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
627 unsafe fn initializer(&self) -> Initializer {
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl<'a> Write for &'a File {
633 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
634 self.inner.write(buf)
636 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
638 #[stable(feature = "rust1", since = "1.0.0")]
639 impl<'a> Seek for &'a File {
640 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
646 /// Creates a blank new set of options ready for configuration.
648 /// All options are initially set to `false`.
653 /// use std::fs::OpenOptions;
655 /// let mut options = OpenOptions::new();
656 /// let file = options.read(true).open("foo.txt");
658 #[stable(feature = "rust1", since = "1.0.0")]
659 pub fn new() -> OpenOptions {
660 OpenOptions(fs_imp::OpenOptions::new())
663 /// Sets the option for read access.
665 /// This option, when true, will indicate that the file should be
666 /// `read`-able if opened.
671 /// use std::fs::OpenOptions;
673 /// let file = OpenOptions::new().read(true).open("foo.txt");
675 #[stable(feature = "rust1", since = "1.0.0")]
676 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
677 self.0.read(read); self
680 /// Sets the option for write access.
682 /// This option, when true, will indicate that the file should be
683 /// `write`-able if opened.
685 /// If the file already exists, any write calls on it will overwrite its
686 /// contents, without truncating it.
691 /// use std::fs::OpenOptions;
693 /// let file = OpenOptions::new().write(true).open("foo.txt");
695 #[stable(feature = "rust1", since = "1.0.0")]
696 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
697 self.0.write(write); self
700 /// Sets the option for the append mode.
702 /// This option, when true, means that writes will append to a file instead
703 /// of overwriting previous contents.
704 /// Note that setting `.write(true).append(true)` has the same effect as
705 /// setting only `.append(true)`.
707 /// For most filesystems, the operating system guarantees that all writes are
708 /// atomic: no writes get mangled because another process writes at the same
711 /// One maybe obvious note when using append-mode: make sure that all data
712 /// that belongs together is written to the file in one operation. This
713 /// can be done by concatenating strings before passing them to [`write()`],
714 /// or using a buffered writer (with a buffer of adequate size),
715 /// and calling [`flush()`] when the message is complete.
717 /// If a file is opened with both read and append access, beware that after
718 /// opening, and after every write, the position for reading may be set at the
719 /// end of the file. So, before writing, save the current position (using
720 /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`), and restore it before the next read.
724 /// This function doesn't create the file if it doesn't exist. Use the [`create`]
727 /// [`write()`]: ../../std/fs/struct.File.html#method.write
728 /// [`flush()`]: ../../std/fs/struct.File.html#method.flush
729 /// [`seek`]: ../../std/fs/struct.File.html#method.seek
730 /// [`SeekFrom`]: ../../std/io/enum.SeekFrom.html
731 /// [`Current`]: ../../std/io/enum.SeekFrom.html#variant.Current
732 /// [`create`]: #method.create
737 /// use std::fs::OpenOptions;
739 /// let file = OpenOptions::new().append(true).open("foo.txt");
741 #[stable(feature = "rust1", since = "1.0.0")]
742 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
743 self.0.append(append); self
746 /// Sets the option for truncating a previous file.
748 /// If a file is successfully opened with this option set it will truncate
749 /// the file to 0 length if it already exists.
751 /// The file must be opened with write access for truncate to work.
756 /// use std::fs::OpenOptions;
758 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
760 #[stable(feature = "rust1", since = "1.0.0")]
761 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
762 self.0.truncate(truncate); self
765 /// Sets the option for creating a new file.
767 /// This option indicates whether a new file will be created if the file
768 /// does not yet already exist.
770 /// In order for the file to be created, [`write`] or [`append`] access must
773 /// [`write`]: #method.write
774 /// [`append`]: #method.append
779 /// use std::fs::OpenOptions;
781 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
783 #[stable(feature = "rust1", since = "1.0.0")]
784 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
785 self.0.create(create); self
788 /// Sets the option to always create a new file.
790 /// This option indicates whether a new file will be created.
791 /// No file is allowed to exist at the target location, also no (dangling)
794 /// This option is useful because it is atomic. Otherwise between checking
795 /// whether a file exists and creating a new one, the file may have been
796 /// created by another process (a TOCTOU race condition / attack).
798 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
801 /// The file must be opened with write or append access in order to create
804 /// [`.create()`]: #method.create
805 /// [`.truncate()`]: #method.truncate
810 /// use std::fs::OpenOptions;
812 /// let file = OpenOptions::new().write(true)
813 /// .create_new(true)
814 /// .open("foo.txt");
816 #[stable(feature = "expand_open_options2", since = "1.9.0")]
817 pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
818 self.0.create_new(create_new); self
821 /// Opens a file at `path` with the options specified by `self`.
825 /// This function will return an error under a number of different
826 /// circumstances. Some of these error conditions are listed here, together
827 /// with their [`ErrorKind`]. The mapping to [`ErrorKind`]s is not part of
828 /// the compatibility contract of the function, especially the `Other` kind
829 /// might change to more specific kinds in the future.
831 /// * [`NotFound`]: The specified file does not exist and neither `create`
832 /// or `create_new` is set.
833 /// * [`NotFound`]: One of the directory components of the file path does
835 /// * [`PermissionDenied`]: The user lacks permission to get the specified
836 /// access rights for the file.
837 /// * [`PermissionDenied`]: The user lacks permission to open one of the
838 /// directory components of the specified path.
839 /// * [`AlreadyExists`]: `create_new` was specified and the file already
841 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
842 /// without write access, no access mode set, etc.).
843 /// * [`Other`]: One of the directory components of the specified file path
844 /// was not, in fact, a directory.
845 /// * [`Other`]: Filesystem-level errors: full disk, write permission
846 /// requested on a read-only file system, exceeded disk quota, too many
847 /// open files, too long filename, too many symbolic links in the
848 /// specified path (Unix-like systems only), etc.
853 /// use std::fs::OpenOptions;
855 /// let file = OpenOptions::new().open("foo.txt");
858 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
859 /// [`AlreadyExists`]: ../io/enum.ErrorKind.html#variant.AlreadyExists
860 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
861 /// [`NotFound`]: ../io/enum.ErrorKind.html#variant.NotFound
862 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
863 /// [`PermissionDenied`]: ../io/enum.ErrorKind.html#variant.PermissionDenied
864 #[stable(feature = "rust1", since = "1.0.0")]
865 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
866 self._open(path.as_ref())
869 fn _open(&self, path: &Path) -> io::Result<File> {
870 let inner = fs_imp::File::open(path, &self.0)?;
875 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
876 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
880 /// Returns the file type for this metadata.
885 /// fn main() -> std::io::Result<()> {
888 /// let metadata = fs::metadata("foo.txt")?;
890 /// println!("{:?}", metadata.file_type());
894 #[stable(feature = "file_type", since = "1.1.0")]
895 pub fn file_type(&self) -> FileType {
896 FileType(self.0.file_type())
899 /// Returns whether this metadata is for a directory. The
900 /// result is mutually exclusive to the result of
901 /// [`is_file`], and will be false for symlink metadata
902 /// obtained from [`symlink_metadata`].
904 /// [`is_file`]: struct.Metadata.html#method.is_file
905 /// [`symlink_metadata`]: fn.symlink_metadata.html
910 /// fn main() -> std::io::Result<()> {
913 /// let metadata = fs::metadata("foo.txt")?;
915 /// assert!(!metadata.is_dir());
919 #[stable(feature = "rust1", since = "1.0.0")]
920 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
922 /// Returns whether this metadata is for a regular file. The
923 /// result is mutually exclusive to the result of
924 /// [`is_dir`], and will be false for symlink metadata
925 /// obtained from [`symlink_metadata`].
927 /// [`is_dir`]: struct.Metadata.html#method.is_dir
928 /// [`symlink_metadata`]: fn.symlink_metadata.html
935 /// fn main() -> std::io::Result<()> {
936 /// let metadata = fs::metadata("foo.txt")?;
938 /// assert!(metadata.is_file());
942 #[stable(feature = "rust1", since = "1.0.0")]
943 pub fn is_file(&self) -> bool { self.file_type().is_file() }
945 /// Returns the size of the file, in bytes, this metadata is for.
952 /// fn main() -> std::io::Result<()> {
953 /// let metadata = fs::metadata("foo.txt")?;
955 /// assert_eq!(0, metadata.len());
959 #[stable(feature = "rust1", since = "1.0.0")]
960 pub fn len(&self) -> u64 { self.0.size() }
962 /// Returns the permissions of the file this metadata is for.
969 /// fn main() -> std::io::Result<()> {
970 /// let metadata = fs::metadata("foo.txt")?;
972 /// assert!(!metadata.permissions().readonly());
976 #[stable(feature = "rust1", since = "1.0.0")]
977 pub fn permissions(&self) -> Permissions {
978 Permissions(self.0.perm())
981 /// Returns the last modification time listed in this metadata.
983 /// The returned value corresponds to the `mtime` field of `stat` on Unix
984 /// platforms and the `ftLastWriteTime` field on Windows platforms.
988 /// This field may not be available on all platforms, and will return an
989 /// `Err` on platforms where it is not available.
996 /// fn main() -> std::io::Result<()> {
997 /// let metadata = fs::metadata("foo.txt")?;
999 /// if let Ok(time) = metadata.modified() {
1000 /// println!("{:?}", time);
1002 /// println!("Not supported on this platform");
1007 #[stable(feature = "fs_time", since = "1.10.0")]
1008 pub fn modified(&self) -> io::Result<SystemTime> {
1009 self.0.modified().map(FromInner::from_inner)
1012 /// Returns the last access time of this metadata.
1014 /// The returned value corresponds to the `atime` field of `stat` on Unix
1015 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1017 /// Note that not all platforms will keep this field update in a file's
1018 /// metadata, for example Windows has an option to disable updating this
1019 /// time when files are accessed and Linux similarly has `noatime`.
1023 /// This field may not be available on all platforms, and will return an
1024 /// `Err` on platforms where it is not available.
1031 /// fn main() -> std::io::Result<()> {
1032 /// let metadata = fs::metadata("foo.txt")?;
1034 /// if let Ok(time) = metadata.accessed() {
1035 /// println!("{:?}", time);
1037 /// println!("Not supported on this platform");
1042 #[stable(feature = "fs_time", since = "1.10.0")]
1043 pub fn accessed(&self) -> io::Result<SystemTime> {
1044 self.0.accessed().map(FromInner::from_inner)
1047 /// Returns the creation time listed in this metadata.
1049 /// The returned value corresponds to the `birthtime` field of `stat` on
1050 /// Unix platforms and the `ftCreationTime` field on Windows platforms.
1054 /// This field may not be available on all platforms, and will return an
1055 /// `Err` on platforms where it is not available.
1062 /// fn main() -> std::io::Result<()> {
1063 /// let metadata = fs::metadata("foo.txt")?;
1065 /// if let Ok(time) = metadata.created() {
1066 /// println!("{:?}", time);
1068 /// println!("Not supported on this platform");
1073 #[stable(feature = "fs_time", since = "1.10.0")]
1074 pub fn created(&self) -> io::Result<SystemTime> {
1075 self.0.created().map(FromInner::from_inner)
1079 #[stable(feature = "std_debug", since = "1.16.0")]
1080 impl fmt::Debug for Metadata {
1081 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1082 f.debug_struct("Metadata")
1083 .field("file_type", &self.file_type())
1084 .field("is_dir", &self.is_dir())
1085 .field("is_file", &self.is_file())
1086 .field("permissions", &self.permissions())
1087 .field("modified", &self.modified())
1088 .field("accessed", &self.accessed())
1089 .field("created", &self.created())
1094 impl AsInner<fs_imp::FileAttr> for Metadata {
1095 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
1099 /// Returns whether these permissions describe a readonly (unwritable) file.
1104 /// use std::fs::File;
1106 /// fn main() -> std::io::Result<()> {
1107 /// let mut f = File::create("foo.txt")?;
1108 /// let metadata = f.metadata()?;
1110 /// assert_eq!(false, metadata.permissions().readonly());
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 pub fn readonly(&self) -> bool { self.0.readonly() }
1117 /// Modifies the readonly flag for this set of permissions. If the
1118 /// `readonly` argument is `true`, using the resulting `Permission` will
1119 /// update file permissions to forbid writing. Conversely, if it's `false`,
1120 /// using the resulting `Permission` will update file permissions to allow
1123 /// This operation does **not** modify the filesystem. To modify the
1124 /// filesystem use the [`fs::set_permissions`] function.
1126 /// [`fs::set_permissions`]: fn.set_permissions.html
1131 /// use std::fs::File;
1133 /// fn main() -> std::io::Result<()> {
1134 /// let f = File::create("foo.txt")?;
1135 /// let metadata = f.metadata()?;
1136 /// let mut permissions = metadata.permissions();
1138 /// permissions.set_readonly(true);
1140 /// // filesystem doesn't change
1141 /// assert_eq!(false, metadata.permissions().readonly());
1143 /// // just this particular `permissions`.
1144 /// assert_eq!(true, permissions.readonly());
1148 #[stable(feature = "rust1", since = "1.0.0")]
1149 pub fn set_readonly(&mut self, readonly: bool) {
1150 self.0.set_readonly(readonly)
1155 /// Test whether this file type represents a directory. The
1156 /// result is mutually exclusive to the results of
1157 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1160 /// [`is_file`]: struct.FileType.html#method.is_file
1161 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1166 /// fn main() -> std::io::Result<()> {
1169 /// let metadata = fs::metadata("foo.txt")?;
1170 /// let file_type = metadata.file_type();
1172 /// assert_eq!(file_type.is_dir(), false);
1176 #[stable(feature = "file_type", since = "1.1.0")]
1177 pub fn is_dir(&self) -> bool { self.0.is_dir() }
1179 /// Test whether this file type represents a regular file.
1180 /// The result is mutually exclusive to the results of
1181 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1184 /// [`is_dir`]: struct.FileType.html#method.is_dir
1185 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1190 /// fn main() -> std::io::Result<()> {
1193 /// let metadata = fs::metadata("foo.txt")?;
1194 /// let file_type = metadata.file_type();
1196 /// assert_eq!(file_type.is_file(), true);
1200 #[stable(feature = "file_type", since = "1.1.0")]
1201 pub fn is_file(&self) -> bool { self.0.is_file() }
1203 /// Test whether this file type represents a symbolic link.
1204 /// The result is mutually exclusive to the results of
1205 /// [`is_dir`] and [`is_file`]; only zero or one of these
1208 /// The underlying [`Metadata`] struct needs to be retrieved
1209 /// with the [`fs::symlink_metadata`] function and not the
1210 /// [`fs::metadata`] function. The [`fs::metadata`] function
1211 /// follows symbolic links, so [`is_symlink`] would always
1212 /// return false for the target file.
1214 /// [`Metadata`]: struct.Metadata.html
1215 /// [`fs::metadata`]: fn.metadata.html
1216 /// [`fs::symlink_metadata`]: fn.symlink_metadata.html
1217 /// [`is_dir`]: struct.FileType.html#method.is_dir
1218 /// [`is_file`]: struct.FileType.html#method.is_file
1219 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1226 /// fn main() -> std::io::Result<()> {
1227 /// let metadata = fs::symlink_metadata("foo.txt")?;
1228 /// let file_type = metadata.file_type();
1230 /// assert_eq!(file_type.is_symlink(), false);
1234 #[stable(feature = "file_type", since = "1.1.0")]
1235 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
1238 impl AsInner<fs_imp::FileType> for FileType {
1239 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
1242 impl FromInner<fs_imp::FilePermissions> for Permissions {
1243 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1248 impl AsInner<fs_imp::FilePermissions> for Permissions {
1249 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 impl Iterator for ReadDir {
1254 type Item = io::Result<DirEntry>;
1256 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1257 self.0.next().map(|entry| entry.map(DirEntry))
1262 /// Returns the full path to the file that this entry represents.
1264 /// The full path is created by joining the original path to `read_dir`
1265 /// with the filename of this entry.
1272 /// fn main() -> std::io::Result<()> {
1273 /// for entry in fs::read_dir(".")? {
1274 /// let dir = entry?;
1275 /// println!("{:?}", dir.path());
1281 /// This prints output like:
1284 /// "./whatever.txt"
1286 /// "./hello_world.rs"
1289 /// The exact text, of course, depends on what files you have in `.`.
1290 #[stable(feature = "rust1", since = "1.0.0")]
1291 pub fn path(&self) -> PathBuf { self.0.path() }
1293 /// Return the metadata for the file that this entry points at.
1295 /// This function will not traverse symlinks if this entry points at a
1298 /// # Platform-specific behavior
1300 /// On Windows this function is cheap to call (no extra system calls
1301 /// needed), but on Unix platforms this function is the equivalent of
1302 /// calling `symlink_metadata` on the path.
1309 /// if let Ok(entries) = fs::read_dir(".") {
1310 /// for entry in entries {
1311 /// if let Ok(entry) = entry {
1312 /// // Here, `entry` is a `DirEntry`.
1313 /// if let Ok(metadata) = entry.metadata() {
1314 /// // Now let's show our entry's permissions!
1315 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1317 /// println!("Couldn't get metadata for {:?}", entry.path());
1323 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1324 pub fn metadata(&self) -> io::Result<Metadata> {
1325 self.0.metadata().map(Metadata)
1328 /// Return the file type for the file that this entry points at.
1330 /// This function will not traverse symlinks if this entry points at a
1333 /// # Platform-specific behavior
1335 /// On Windows and most Unix platforms this function is free (no extra
1336 /// system calls needed), but some Unix platforms may require the equivalent
1337 /// call to `symlink_metadata` to learn about the target file type.
1344 /// if let Ok(entries) = fs::read_dir(".") {
1345 /// for entry in entries {
1346 /// if let Ok(entry) = entry {
1347 /// // Here, `entry` is a `DirEntry`.
1348 /// if let Ok(file_type) = entry.file_type() {
1349 /// // Now let's show our entry's file type!
1350 /// println!("{:?}: {:?}", entry.path(), file_type);
1352 /// println!("Couldn't get file type for {:?}", entry.path());
1358 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1359 pub fn file_type(&self) -> io::Result<FileType> {
1360 self.0.file_type().map(FileType)
1363 /// Returns the bare file name of this directory entry without any other
1364 /// leading path component.
1371 /// if let Ok(entries) = fs::read_dir(".") {
1372 /// for entry in entries {
1373 /// if let Ok(entry) = entry {
1374 /// // Here, `entry` is a `DirEntry`.
1375 /// println!("{:?}", entry.file_name());
1380 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1381 pub fn file_name(&self) -> OsString {
1386 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1387 impl fmt::Debug for DirEntry {
1388 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1389 f.debug_tuple("DirEntry")
1390 .field(&self.path())
1395 impl AsInner<fs_imp::DirEntry> for DirEntry {
1396 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
1399 /// Removes a file from the filesystem.
1401 /// Note that there is no
1402 /// guarantee that the file is immediately deleted (e.g., depending on
1403 /// platform, other open file descriptors may prevent immediate removal).
1405 /// # Platform-specific behavior
1407 /// This function currently corresponds to the `unlink` function on Unix
1408 /// and the `DeleteFile` function on Windows.
1409 /// Note that, this [may change in the future][changes].
1411 /// [changes]: ../io/index.html#platform-specific-behavior
1415 /// This function will return an error in the following situations, but is not
1416 /// limited to just these cases:
1418 /// * `path` points to a directory.
1419 /// * The user lacks permissions to remove the file.
1426 /// fn main() -> std::io::Result<()> {
1427 /// fs::remove_file("a.txt")?;
1431 #[stable(feature = "rust1", since = "1.0.0")]
1432 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1433 fs_imp::unlink(path.as_ref())
1436 /// Given a path, query the file system to get information about a file,
1439 /// This function will traverse symbolic links to query information about the
1440 /// destination file.
1442 /// # Platform-specific behavior
1444 /// This function currently corresponds to the `stat` function on Unix
1445 /// and the `GetFileAttributesEx` function on Windows.
1446 /// Note that, this [may change in the future][changes].
1448 /// [changes]: ../io/index.html#platform-specific-behavior
1452 /// This function will return an error in the following situations, but is not
1453 /// limited to just these cases:
1455 /// * The user lacks permissions to perform `metadata` call on `path`.
1456 /// * `path` does not exist.
1463 /// fn main() -> std::io::Result<()> {
1464 /// let attr = fs::metadata("/some/file/path.txt")?;
1465 /// // inspect attr ...
1469 #[stable(feature = "rust1", since = "1.0.0")]
1470 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1471 fs_imp::stat(path.as_ref()).map(Metadata)
1474 /// Query the metadata about a file without following symlinks.
1476 /// # Platform-specific behavior
1478 /// This function currently corresponds to the `lstat` function on Unix
1479 /// and the `GetFileAttributesEx` function on Windows.
1480 /// Note that, this [may change in the future][changes].
1482 /// [changes]: ../io/index.html#platform-specific-behavior
1486 /// This function will return an error in the following situations, but is not
1487 /// limited to just these cases:
1489 /// * The user lacks permissions to perform `metadata` call on `path`.
1490 /// * `path` does not exist.
1497 /// fn main() -> std::io::Result<()> {
1498 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1499 /// // inspect attr ...
1503 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1504 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1505 fs_imp::lstat(path.as_ref()).map(Metadata)
1508 /// Rename a file or directory to a new name, replacing the original file if
1509 /// `to` already exists.
1511 /// This will not work if the new name is on a different mount point.
1513 /// # Platform-specific behavior
1515 /// This function currently corresponds to the `rename` function on Unix
1516 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1518 /// Because of this, the behavior when both `from` and `to` exist differs. On
1519 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1520 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1521 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1523 /// Note that, this [may change in the future][changes].
1525 /// [changes]: ../io/index.html#platform-specific-behavior
1529 /// This function will return an error in the following situations, but is not
1530 /// limited to just these cases:
1532 /// * `from` does not exist.
1533 /// * The user lacks permissions to view contents.
1534 /// * `from` and `to` are on separate filesystems.
1541 /// fn main() -> std::io::Result<()> {
1542 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1546 #[stable(feature = "rust1", since = "1.0.0")]
1547 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1548 fs_imp::rename(from.as_ref(), to.as_ref())
1551 /// Copies the contents of one file to another. This function will also
1552 /// copy the permission bits of the original file to the destination file.
1554 /// This function will **overwrite** the contents of `to`.
1556 /// Note that if `from` and `to` both point to the same file, then the file
1557 /// will likely get truncated by this operation.
1559 /// On success, the total number of bytes copied is returned and it is equal to
1560 /// the length of the `to` file as reported by `metadata`.
1562 /// If you’re wanting to copy the contents of one file to another and you’re
1563 /// working with [`File`]s, see the [`io::copy`] function.
1565 /// [`io::copy`]: ../io/fn.copy.html
1566 /// [`File`]: ./struct.File.html
1568 /// # Platform-specific behavior
1570 /// This function currently corresponds to the `open` function in Unix
1571 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1572 /// `O_CLOEXEC` is set for returned file descriptors.
1573 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1574 /// NTFS streams are copied but only the size of the main stream is returned by
1576 /// Note that, this [may change in the future][changes].
1578 /// [changes]: ../io/index.html#platform-specific-behavior
1582 /// This function will return an error in the following situations, but is not
1583 /// limited to just these cases:
1585 /// * The `from` path is not a file.
1586 /// * The `from` file does not exist.
1587 /// * The current process does not have the permission rights to access
1588 /// `from` or write `to`.
1595 /// fn main() -> std::io::Result<()> {
1596 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1602 fs_imp::copy(from.as_ref(), to.as_ref())
1605 /// Creates a new hard link on the filesystem.
1607 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1608 /// often require these two paths to both be located on the same filesystem.
1610 /// # Platform-specific behavior
1612 /// This function currently corresponds to the `link` function on Unix
1613 /// and the `CreateHardLink` function on Windows.
1614 /// Note that, this [may change in the future][changes].
1616 /// [changes]: ../io/index.html#platform-specific-behavior
1620 /// This function will return an error in the following situations, but is not
1621 /// limited to just these cases:
1623 /// * The `src` path is not a file or doesn't exist.
1630 /// fn main() -> std::io::Result<()> {
1631 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1637 fs_imp::link(src.as_ref(), dst.as_ref())
1640 /// Creates a new symbolic link on the filesystem.
1642 /// The `dst` path will be a symbolic link pointing to the `src` path.
1643 /// On Windows, this will be a file symlink, not a directory symlink;
1644 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1645 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1646 /// used instead to make the intent explicit.
1648 /// [`std::os::unix::fs::symlink`]: ../os/unix/fs/fn.symlink.html
1649 /// [`std::os::windows::fs::symlink_file`]: ../os/windows/fs/fn.symlink_file.html
1650 /// [`symlink_dir`]: ../os/windows/fs/fn.symlink_dir.html
1658 /// fn main() -> std::io::Result<()> {
1659 /// fs::soft_link("a.txt", "b.txt")?;
1663 #[stable(feature = "rust1", since = "1.0.0")]
1664 #[rustc_deprecated(since = "1.1.0",
1665 reason = "replaced with std::os::unix::fs::symlink and \
1666 std::os::windows::fs::{symlink_file, symlink_dir}")]
1667 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1668 fs_imp::symlink(src.as_ref(), dst.as_ref())
1671 /// Reads a symbolic link, returning the file that the link points to.
1673 /// # Platform-specific behavior
1675 /// This function currently corresponds to the `readlink` function on Unix
1676 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1677 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1678 /// Note that, this [may change in the future][changes].
1680 /// [changes]: ../io/index.html#platform-specific-behavior
1684 /// This function will return an error in the following situations, but is not
1685 /// limited to just these cases:
1687 /// * `path` is not a symbolic link.
1688 /// * `path` does not exist.
1695 /// fn main() -> std::io::Result<()> {
1696 /// let path = fs::read_link("a.txt")?;
1700 #[stable(feature = "rust1", since = "1.0.0")]
1701 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1702 fs_imp::readlink(path.as_ref())
1705 /// Returns the canonical, absolute form of a path with all intermediate
1706 /// components normalized and symbolic links resolved.
1708 /// # Platform-specific behavior
1710 /// This function currently corresponds to the `realpath` function on Unix
1711 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1712 /// Note that, this [may change in the future][changes].
1714 /// On Windows, this converts the path to use [extended length path][path]
1715 /// syntax, which allows your program to use longer path names, but means you
1716 /// can only join backslash-delimited paths to it, and it may be incompatible
1717 /// with other applications (if passed to the application on the command-line,
1718 /// or written to a file another application may read).
1720 /// [changes]: ../io/index.html#platform-specific-behavior
1721 /// [path]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
1725 /// This function will return an error in the following situations, but is not
1726 /// limited to just these cases:
1728 /// * `path` does not exist.
1729 /// * A non-final component in path is not a directory.
1736 /// fn main() -> std::io::Result<()> {
1737 /// let path = fs::canonicalize("../a/../foo.txt")?;
1741 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1742 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1743 fs_imp::canonicalize(path.as_ref())
1746 /// Creates a new, empty directory at the provided path
1748 /// # Platform-specific behavior
1750 /// This function currently corresponds to the `mkdir` function on Unix
1751 /// and the `CreateDirectory` function on Windows.
1752 /// Note that, this [may change in the future][changes].
1754 /// [changes]: ../io/index.html#platform-specific-behavior
1756 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1757 /// return an error. To create a directory and all its missing parents at the
1758 /// same time, use the [`create_dir_all`] function.
1762 /// This function will return an error in the following situations, but is not
1763 /// limited to just these cases:
1765 /// * User lacks permissions to create directory at `path`.
1766 /// * A parent of the given path doesn't exist. (To create a directory and all
1767 /// its missing parents at the same time, use the [`create_dir_all`]
1769 /// * `path` already exists.
1776 /// fn main() -> std::io::Result<()> {
1777 /// fs::create_dir("/some/dir")?;
1781 #[stable(feature = "rust1", since = "1.0.0")]
1782 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1783 DirBuilder::new().create(path.as_ref())
1786 /// Recursively create a directory and all of its parent components if they
1789 /// # Platform-specific behavior
1791 /// This function currently corresponds to the `mkdir` function on Unix
1792 /// and the `CreateDirectory` function on Windows.
1793 /// Note that, this [may change in the future][changes].
1795 /// [changes]: ../io/index.html#platform-specific-behavior
1799 /// This function will return an error in the following situations, but is not
1800 /// limited to just these cases:
1802 /// * If any directory in the path specified by `path`
1803 /// does not already exist and it could not be created otherwise. The specific
1804 /// error conditions for when a directory is being created (after it is
1805 /// determined to not exist) are outlined by [`fs::create_dir`].
1807 /// Notable exception is made for situations where any of the directories
1808 /// specified in the `path` could not be created as it was being created concurrently.
1809 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1810 /// concurrently from multiple threads or processes is guaranteed not to fail
1811 /// due to a race condition with itself.
1813 /// [`fs::create_dir`]: fn.create_dir.html
1820 /// fn main() -> std::io::Result<()> {
1821 /// fs::create_dir_all("/some/dir")?;
1825 #[stable(feature = "rust1", since = "1.0.0")]
1826 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1827 DirBuilder::new().recursive(true).create(path.as_ref())
1830 /// Removes an existing, empty directory.
1832 /// # Platform-specific behavior
1834 /// This function currently corresponds to the `rmdir` function on Unix
1835 /// and the `RemoveDirectory` function on Windows.
1836 /// Note that, this [may change in the future][changes].
1838 /// [changes]: ../io/index.html#platform-specific-behavior
1842 /// This function will return an error in the following situations, but is not
1843 /// limited to just these cases:
1845 /// * The user lacks permissions to remove the directory at the provided `path`.
1846 /// * The directory isn't empty.
1853 /// fn main() -> std::io::Result<()> {
1854 /// fs::remove_dir("/some/dir")?;
1858 #[stable(feature = "rust1", since = "1.0.0")]
1859 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1860 fs_imp::rmdir(path.as_ref())
1863 /// Removes a directory at this path, after removing all its contents. Use
1866 /// This function does **not** follow symbolic links and it will simply remove the
1867 /// symbolic link itself.
1869 /// # Platform-specific behavior
1871 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1872 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1874 /// Note that, this [may change in the future][changes].
1876 /// [changes]: ../io/index.html#platform-specific-behavior
1880 /// See [`fs::remove_file`] and [`fs::remove_dir`].
1882 /// [`fs::remove_file`]: fn.remove_file.html
1883 /// [`fs::remove_dir`]: fn.remove_dir.html
1890 /// fn main() -> std::io::Result<()> {
1891 /// fs::remove_dir_all("/some/dir")?;
1895 #[stable(feature = "rust1", since = "1.0.0")]
1896 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1897 fs_imp::remove_dir_all(path.as_ref())
1900 /// Returns an iterator over the entries within a directory.
1902 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
1903 /// New errors may be encountered after an iterator is initially constructed.
1905 /// [`io::Result`]: ../io/type.Result.html
1906 /// [`DirEntry`]: struct.DirEntry.html
1908 /// # Platform-specific behavior
1910 /// This function currently corresponds to the `opendir` function on Unix
1911 /// and the `FindFirstFile` function on Windows.
1912 /// Note that, this [may change in the future][changes].
1914 /// [changes]: ../io/index.html#platform-specific-behavior
1918 /// This function will return an error in the following situations, but is not
1919 /// limited to just these cases:
1921 /// * The provided `path` doesn't exist.
1922 /// * The process lacks permissions to view the contents.
1923 /// * The `path` points at a non-directory file.
1929 /// use std::fs::{self, DirEntry};
1930 /// use std::path::Path;
1932 /// // one possible implementation of walking a directory only visiting files
1933 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1934 /// if dir.is_dir() {
1935 /// for entry in fs::read_dir(dir)? {
1936 /// let entry = entry?;
1937 /// let path = entry.path();
1938 /// if path.is_dir() {
1939 /// visit_dirs(&path, cb)?;
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1950 fs_imp::readdir(path.as_ref()).map(ReadDir)
1953 /// Changes the permissions found on a file or a directory.
1955 /// # Platform-specific behavior
1957 /// This function currently corresponds to the `chmod` function on Unix
1958 /// and the `SetFileAttributes` function on Windows.
1959 /// Note that, this [may change in the future][changes].
1961 /// [changes]: ../io/index.html#platform-specific-behavior
1965 /// This function will return an error in the following situations, but is not
1966 /// limited to just these cases:
1968 /// * `path` does not exist.
1969 /// * The user lacks the permission to change attributes of the file.
1976 /// fn main() -> std::io::Result<()> {
1977 /// let mut perms = fs::metadata("foo.txt")?.permissions();
1978 /// perms.set_readonly(true);
1979 /// fs::set_permissions("foo.txt", perms)?;
1983 #[stable(feature = "set_permissions", since = "1.1.0")]
1984 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1986 fs_imp::set_perm(path.as_ref(), perm.0)
1990 /// Creates a new set of options with default mode/security settings for all
1991 /// platforms and also non-recursive.
1996 /// use std::fs::DirBuilder;
1998 /// let builder = DirBuilder::new();
2000 #[stable(feature = "dir_builder", since = "1.6.0")]
2001 pub fn new() -> DirBuilder {
2003 inner: fs_imp::DirBuilder::new(),
2008 /// Indicates that directories should be created recursively, creating all
2009 /// parent directories. Parents that do not exist are created with the same
2010 /// security and permissions settings.
2012 /// This option defaults to `false`.
2017 /// use std::fs::DirBuilder;
2019 /// let mut builder = DirBuilder::new();
2020 /// builder.recursive(true);
2022 #[stable(feature = "dir_builder", since = "1.6.0")]
2023 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2024 self.recursive = recursive;
2028 /// Create the specified directory with the options configured in this
2031 /// It is considered an error if the directory already exists unless
2032 /// recursive mode is enabled.
2037 /// use std::fs::{self, DirBuilder};
2039 /// let path = "/tmp/foo/bar/baz";
2040 /// DirBuilder::new()
2041 /// .recursive(true)
2042 /// .create(path).unwrap();
2044 /// assert!(fs::metadata(path).unwrap().is_dir());
2046 #[stable(feature = "dir_builder", since = "1.6.0")]
2047 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2048 self._create(path.as_ref())
2051 fn _create(&self, path: &Path) -> io::Result<()> {
2053 self.create_dir_all(path)
2055 self.inner.mkdir(path)
2059 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2060 if path == Path::new("") {
2064 match self.inner.mkdir(path) {
2065 Ok(()) => return Ok(()),
2066 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2067 Err(_) if path.is_dir() => return Ok(()),
2068 Err(e) => return Err(e),
2070 match path.parent() {
2071 Some(p) => self.create_dir_all(p)?,
2072 None => return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree")),
2074 match self.inner.mkdir(path) {
2076 Err(_) if path.is_dir() => Ok(()),
2082 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2083 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2088 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
2092 use fs::{self, File, OpenOptions};
2093 use io::{ErrorKind, SeekFrom};
2095 use rand::{rngs::StdRng, FromEntropy, RngCore};
2097 use sys_common::io::test::{TempDir, tmpdir};
2101 use os::windows::fs::{symlink_dir, symlink_file};
2103 use sys::fs::symlink_junction;
2105 use os::unix::fs::symlink as symlink_dir;
2107 use os::unix::fs::symlink as symlink_file;
2109 use os::unix::fs::symlink as symlink_junction;
2111 macro_rules! check { ($e:expr) => (
2114 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
2119 macro_rules! error { ($e:expr, $s:expr) => (
2121 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2122 Err(ref err) => assert!(err.raw_os_error() == Some($s),
2123 format!("`{}` did not have a code of `{}`", err, $s))
2128 macro_rules! error { ($e:expr, $s:expr) => ( error_contains!($e, $s) ) }
2130 macro_rules! error_contains { ($e:expr, $s:expr) => (
2132 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2133 Err(ref err) => assert!(err.to_string().contains($s),
2134 format!("`{}` did not contain `{}`", err, $s))
2138 // Several test fail on windows if the user does not have permission to
2139 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
2140 // disabling these test on Windows, use this function to test whether we
2141 // have permission, and return otherwise. This way, we still don't run these
2142 // tests most of the time, but at least we do if the user has the right
2144 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
2145 if cfg!(unix) { return true }
2146 let link = tmpdir.join("some_hopefully_unique_link_name");
2148 match symlink_file(r"nonexisting_target", link) {
2150 // ERROR_PRIVILEGE_NOT_HELD = 1314
2151 Err(ref err) if err.raw_os_error() == Some(1314) => false,
2157 fn file_test_io_smoke_test() {
2158 let message = "it's alright. have a good time";
2159 let tmpdir = tmpdir();
2160 let filename = &tmpdir.join("file_rt_io_file_test.txt");
2162 let mut write_stream = check!(File::create(filename));
2163 check!(write_stream.write(message.as_bytes()));
2166 let mut read_stream = check!(File::open(filename));
2167 let mut read_buf = [0; 1028];
2168 let read_str = match check!(read_stream.read(&mut read_buf)) {
2169 0 => panic!("shouldn't happen"),
2170 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
2172 assert_eq!(read_str, message);
2174 check!(fs::remove_file(filename));
2178 fn invalid_path_raises() {
2179 let tmpdir = tmpdir();
2180 let filename = &tmpdir.join("file_that_does_not_exist.txt");
2181 let result = File::open(filename);
2184 error!(result, "No such file or directory");
2186 error!(result, 2); // ERROR_FILE_NOT_FOUND
2190 fn file_test_iounlinking_invalid_path_should_raise_condition() {
2191 let tmpdir = tmpdir();
2192 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
2194 let result = fs::remove_file(filename);
2197 error!(result, "No such file or directory");
2199 error!(result, 2); // ERROR_FILE_NOT_FOUND
2203 fn file_test_io_non_positional_read() {
2204 let message: &str = "ten-four";
2205 let mut read_mem = [0; 8];
2206 let tmpdir = tmpdir();
2207 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
2209 let mut rw_stream = check!(File::create(filename));
2210 check!(rw_stream.write(message.as_bytes()));
2213 let mut read_stream = check!(File::open(filename));
2215 let read_buf = &mut read_mem[0..4];
2216 check!(read_stream.read(read_buf));
2219 let read_buf = &mut read_mem[4..8];
2220 check!(read_stream.read(read_buf));
2223 check!(fs::remove_file(filename));
2224 let read_str = str::from_utf8(&read_mem).unwrap();
2225 assert_eq!(read_str, message);
2229 fn file_test_io_seek_and_tell_smoke_test() {
2230 let message = "ten-four";
2231 let mut read_mem = [0; 4];
2232 let set_cursor = 4 as u64;
2233 let tell_pos_pre_read;
2234 let tell_pos_post_read;
2235 let tmpdir = tmpdir();
2236 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
2238 let mut rw_stream = check!(File::create(filename));
2239 check!(rw_stream.write(message.as_bytes()));
2242 let mut read_stream = check!(File::open(filename));
2243 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
2244 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
2245 check!(read_stream.read(&mut read_mem));
2246 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
2248 check!(fs::remove_file(filename));
2249 let read_str = str::from_utf8(&read_mem).unwrap();
2250 assert_eq!(read_str, &message[4..8]);
2251 assert_eq!(tell_pos_pre_read, set_cursor);
2252 assert_eq!(tell_pos_post_read, message.len() as u64);
2256 fn file_test_io_seek_and_write() {
2257 let initial_msg = "food-is-yummy";
2258 let overwrite_msg = "-the-bar!!";
2259 let final_msg = "foo-the-bar!!";
2261 let mut read_mem = [0; 13];
2262 let tmpdir = tmpdir();
2263 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
2265 let mut rw_stream = check!(File::create(filename));
2266 check!(rw_stream.write(initial_msg.as_bytes()));
2267 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
2268 check!(rw_stream.write(overwrite_msg.as_bytes()));
2271 let mut read_stream = check!(File::open(filename));
2272 check!(read_stream.read(&mut read_mem));
2274 check!(fs::remove_file(filename));
2275 let read_str = str::from_utf8(&read_mem).unwrap();
2276 assert!(read_str == final_msg);
2280 fn file_test_io_seek_shakedown() {
2282 let initial_msg = "qwer-asdf-zxcv";
2283 let chunk_one: &str = "qwer";
2284 let chunk_two: &str = "asdf";
2285 let chunk_three: &str = "zxcv";
2286 let mut read_mem = [0; 4];
2287 let tmpdir = tmpdir();
2288 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2290 let mut rw_stream = check!(File::create(filename));
2291 check!(rw_stream.write(initial_msg.as_bytes()));
2294 let mut read_stream = check!(File::open(filename));
2296 check!(read_stream.seek(SeekFrom::End(-4)));
2297 check!(read_stream.read(&mut read_mem));
2298 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2300 check!(read_stream.seek(SeekFrom::Current(-9)));
2301 check!(read_stream.read(&mut read_mem));
2302 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2304 check!(read_stream.seek(SeekFrom::Start(0)));
2305 check!(read_stream.read(&mut read_mem));
2306 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2308 check!(fs::remove_file(filename));
2312 fn file_test_io_eof() {
2313 let tmpdir = tmpdir();
2314 let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2315 let mut buf = [0; 256];
2317 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2318 let mut rw = check!(oo.open(&filename));
2319 assert_eq!(check!(rw.read(&mut buf)), 0);
2320 assert_eq!(check!(rw.read(&mut buf)), 0);
2322 check!(fs::remove_file(&filename));
2327 fn file_test_io_read_write_at() {
2328 use os::unix::fs::FileExt;
2330 let tmpdir = tmpdir();
2331 let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2332 let mut buf = [0; 256];
2333 let write1 = "asdf";
2334 let write2 = "qwer-";
2335 let write3 = "-zxcv";
2336 let content = "qwer-asdf-zxcv";
2338 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2339 let mut rw = check!(oo.open(&filename));
2340 assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2341 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2342 assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2343 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2344 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2345 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2346 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2347 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2348 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2349 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2350 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2351 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2352 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2353 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2354 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2355 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2356 assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2357 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2360 let mut read = check!(File::open(&filename));
2361 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2362 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2363 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2364 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2365 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2366 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2367 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2368 assert_eq!(check!(read.read(&mut buf)), write3.len());
2369 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2370 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2371 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2372 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2373 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2374 assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2375 assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2376 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2378 check!(fs::remove_file(&filename));
2383 fn set_get_unix_permissions() {
2384 use os::unix::fs::PermissionsExt;
2386 let tmpdir = tmpdir();
2387 let filename = &tmpdir.join("set_get_unix_permissions");
2388 check!(fs::create_dir(filename));
2391 check!(fs::set_permissions(filename,
2392 fs::Permissions::from_mode(0)));
2393 let metadata0 = check!(fs::metadata(filename));
2394 assert_eq!(mask & metadata0.permissions().mode(), 0);
2396 check!(fs::set_permissions(filename,
2397 fs::Permissions::from_mode(0o1777)));
2398 let metadata1 = check!(fs::metadata(filename));
2399 assert_eq!(mask & metadata1.permissions().mode(), 0o1777);
2404 fn file_test_io_seek_read_write() {
2405 use os::windows::fs::FileExt;
2407 let tmpdir = tmpdir();
2408 let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2409 let mut buf = [0; 256];
2410 let write1 = "asdf";
2411 let write2 = "qwer-";
2412 let write3 = "-zxcv";
2413 let content = "qwer-asdf-zxcv";
2415 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2416 let mut rw = check!(oo.open(&filename));
2417 assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2418 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2419 assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2420 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2421 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2422 assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2423 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2424 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2425 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2426 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2427 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2428 assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2429 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2430 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2431 assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2432 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2435 let mut read = check!(File::open(&filename));
2436 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2437 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2438 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2439 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2440 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2441 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2442 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2443 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2444 assert_eq!(check!(read.read(&mut buf)), write3.len());
2445 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2446 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2447 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2448 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2449 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2450 assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2451 assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2453 check!(fs::remove_file(&filename));
2457 fn file_test_stat_is_correct_on_is_file() {
2458 let tmpdir = tmpdir();
2459 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2461 let mut opts = OpenOptions::new();
2462 let mut fs = check!(opts.read(true).write(true)
2463 .create(true).open(filename));
2465 fs.write(msg.as_bytes()).unwrap();
2467 let fstat_res = check!(fs.metadata());
2468 assert!(fstat_res.is_file());
2470 let stat_res_fn = check!(fs::metadata(filename));
2471 assert!(stat_res_fn.is_file());
2472 let stat_res_meth = check!(filename.metadata());
2473 assert!(stat_res_meth.is_file());
2474 check!(fs::remove_file(filename));
2478 fn file_test_stat_is_correct_on_is_dir() {
2479 let tmpdir = tmpdir();
2480 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2481 check!(fs::create_dir(filename));
2482 let stat_res_fn = check!(fs::metadata(filename));
2483 assert!(stat_res_fn.is_dir());
2484 let stat_res_meth = check!(filename.metadata());
2485 assert!(stat_res_meth.is_dir());
2486 check!(fs::remove_dir(filename));
2490 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2491 let tmpdir = tmpdir();
2492 let dir = &tmpdir.join("fileinfo_false_on_dir");
2493 check!(fs::create_dir(dir));
2494 assert!(!dir.is_file());
2495 check!(fs::remove_dir(dir));
2499 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2500 let tmpdir = tmpdir();
2501 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2502 check!(check!(File::create(file)).write(b"foo"));
2503 assert!(file.exists());
2504 check!(fs::remove_file(file));
2505 assert!(!file.exists());
2509 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2510 let tmpdir = tmpdir();
2511 let dir = &tmpdir.join("before_and_after_dir");
2512 assert!(!dir.exists());
2513 check!(fs::create_dir(dir));
2514 assert!(dir.exists());
2515 assert!(dir.is_dir());
2516 check!(fs::remove_dir(dir));
2517 assert!(!dir.exists());
2521 fn file_test_directoryinfo_readdir() {
2522 let tmpdir = tmpdir();
2523 let dir = &tmpdir.join("di_readdir");
2524 check!(fs::create_dir(dir));
2527 let f = dir.join(&format!("{}.txt", n));
2528 let mut w = check!(File::create(&f));
2529 let msg_str = format!("{}{}", prefix, n.to_string());
2530 let msg = msg_str.as_bytes();
2531 check!(w.write(msg));
2533 let files = check!(fs::read_dir(dir));
2534 let mut mem = [0; 4];
2536 let f = f.unwrap().path();
2538 let n = f.file_stem().unwrap();
2539 check!(check!(File::open(&f)).read(&mut mem));
2540 let read_str = str::from_utf8(&mem).unwrap();
2541 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2542 assert_eq!(expected, read_str);
2544 check!(fs::remove_file(&f));
2546 check!(fs::remove_dir(dir));
2550 fn file_create_new_already_exists_error() {
2551 let tmpdir = tmpdir();
2552 let file = &tmpdir.join("file_create_new_error_exists");
2553 check!(fs::File::create(file));
2554 let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2555 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2559 fn mkdir_path_already_exists_error() {
2560 let tmpdir = tmpdir();
2561 let dir = &tmpdir.join("mkdir_error_twice");
2562 check!(fs::create_dir(dir));
2563 let e = fs::create_dir(dir).unwrap_err();
2564 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2568 fn recursive_mkdir() {
2569 let tmpdir = tmpdir();
2570 let dir = tmpdir.join("d1/d2");
2571 check!(fs::create_dir_all(&dir));
2572 assert!(dir.is_dir())
2576 fn recursive_mkdir_failure() {
2577 let tmpdir = tmpdir();
2578 let dir = tmpdir.join("d1");
2579 let file = dir.join("f1");
2581 check!(fs::create_dir_all(&dir));
2582 check!(File::create(&file));
2584 let result = fs::create_dir_all(&file);
2586 assert!(result.is_err());
2590 fn concurrent_recursive_mkdir() {
2593 let mut dir = dir.join("a");
2595 dir = dir.join("a");
2597 let mut join = vec!();
2599 let dir = dir.clone();
2600 join.push(thread::spawn(move || {
2601 check!(fs::create_dir_all(&dir));
2605 // No `Display` on result of `join()`
2606 join.drain(..).map(|join| join.join().unwrap()).count();
2611 fn recursive_mkdir_slash() {
2612 check!(fs::create_dir_all(Path::new("/")));
2616 fn recursive_mkdir_dot() {
2617 check!(fs::create_dir_all(Path::new(".")));
2621 fn recursive_mkdir_empty() {
2622 check!(fs::create_dir_all(Path::new("")));
2626 fn recursive_rmdir() {
2627 let tmpdir = tmpdir();
2628 let d1 = tmpdir.join("d1");
2629 let dt = d1.join("t");
2630 let dtt = dt.join("t");
2631 let d2 = tmpdir.join("d2");
2632 let canary = d2.join("do_not_delete");
2633 check!(fs::create_dir_all(&dtt));
2634 check!(fs::create_dir_all(&d2));
2635 check!(check!(File::create(&canary)).write(b"foo"));
2636 check!(symlink_junction(&d2, &dt.join("d2")));
2637 let _ = symlink_file(&canary, &d1.join("canary"));
2638 check!(fs::remove_dir_all(&d1));
2640 assert!(!d1.is_dir());
2641 assert!(canary.exists());
2645 fn recursive_rmdir_of_symlink() {
2646 // test we do not recursively delete a symlink but only dirs.
2647 let tmpdir = tmpdir();
2648 let link = tmpdir.join("d1");
2649 let dir = tmpdir.join("d2");
2650 let canary = dir.join("do_not_delete");
2651 check!(fs::create_dir_all(&dir));
2652 check!(check!(File::create(&canary)).write(b"foo"));
2653 check!(symlink_junction(&dir, &link));
2654 check!(fs::remove_dir_all(&link));
2656 assert!(!link.is_dir());
2657 assert!(canary.exists());
2661 // only Windows makes a distinction between file and directory symlinks.
2663 fn recursive_rmdir_of_file_symlink() {
2664 let tmpdir = tmpdir();
2665 if !got_symlink_permission(&tmpdir) { return };
2667 let f1 = tmpdir.join("f1");
2668 let f2 = tmpdir.join("f2");
2669 check!(check!(File::create(&f1)).write(b"foo"));
2670 check!(symlink_file(&f1, &f2));
2671 match fs::remove_dir_all(&f2) {
2672 Ok(..) => panic!("wanted a failure"),
2678 fn unicode_path_is_dir() {
2679 assert!(Path::new(".").is_dir());
2680 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2682 let tmpdir = tmpdir();
2684 let mut dirpath = tmpdir.path().to_path_buf();
2685 dirpath.push("test-가一ー你好");
2686 check!(fs::create_dir(&dirpath));
2687 assert!(dirpath.is_dir());
2689 let mut filepath = dirpath;
2690 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2691 check!(File::create(&filepath)); // ignore return; touch only
2692 assert!(!filepath.is_dir());
2693 assert!(filepath.exists());
2697 fn unicode_path_exists() {
2698 assert!(Path::new(".").exists());
2699 assert!(!Path::new("test/nonexistent-bogus-path").exists());
2701 let tmpdir = tmpdir();
2702 let unicode = tmpdir.path();
2703 let unicode = unicode.join("test-각丁ー再见");
2704 check!(fs::create_dir(&unicode));
2705 assert!(unicode.exists());
2706 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2710 fn copy_file_does_not_exist() {
2711 let from = Path::new("test/nonexistent-bogus-path");
2712 let to = Path::new("test/other-bogus-path");
2714 match fs::copy(&from, &to) {
2717 assert!(!from.exists());
2718 assert!(!to.exists());
2724 fn copy_src_does_not_exist() {
2725 let tmpdir = tmpdir();
2726 let from = Path::new("test/nonexistent-bogus-path");
2727 let to = tmpdir.join("out.txt");
2728 check!(check!(File::create(&to)).write(b"hello"));
2729 assert!(fs::copy(&from, &to).is_err());
2730 assert!(!from.exists());
2731 let mut v = Vec::new();
2732 check!(check!(File::open(&to)).read_to_end(&mut v));
2733 assert_eq!(v, b"hello");
2738 let tmpdir = tmpdir();
2739 let input = tmpdir.join("in.txt");
2740 let out = tmpdir.join("out.txt");
2742 check!(check!(File::create(&input)).write(b"hello"));
2743 check!(fs::copy(&input, &out));
2744 let mut v = Vec::new();
2745 check!(check!(File::open(&out)).read_to_end(&mut v));
2746 assert_eq!(v, b"hello");
2748 assert_eq!(check!(input.metadata()).permissions(),
2749 check!(out.metadata()).permissions());
2753 fn copy_file_dst_dir() {
2754 let tmpdir = tmpdir();
2755 let out = tmpdir.join("out");
2757 check!(File::create(&out));
2758 match fs::copy(&*out, tmpdir.path()) {
2759 Ok(..) => panic!(), Err(..) => {}
2764 fn copy_file_dst_exists() {
2765 let tmpdir = tmpdir();
2766 let input = tmpdir.join("in");
2767 let output = tmpdir.join("out");
2769 check!(check!(File::create(&input)).write("foo".as_bytes()));
2770 check!(check!(File::create(&output)).write("bar".as_bytes()));
2771 check!(fs::copy(&input, &output));
2773 let mut v = Vec::new();
2774 check!(check!(File::open(&output)).read_to_end(&mut v));
2775 assert_eq!(v, b"foo".to_vec());
2779 fn copy_file_src_dir() {
2780 let tmpdir = tmpdir();
2781 let out = tmpdir.join("out");
2783 match fs::copy(tmpdir.path(), &out) {
2784 Ok(..) => panic!(), Err(..) => {}
2786 assert!(!out.exists());
2790 fn copy_file_preserves_perm_bits() {
2791 let tmpdir = tmpdir();
2792 let input = tmpdir.join("in.txt");
2793 let out = tmpdir.join("out.txt");
2795 let attr = check!(check!(File::create(&input)).metadata());
2796 let mut p = attr.permissions();
2797 p.set_readonly(true);
2798 check!(fs::set_permissions(&input, p));
2799 check!(fs::copy(&input, &out));
2800 assert!(check!(out.metadata()).permissions().readonly());
2801 check!(fs::set_permissions(&input, attr.permissions()));
2802 check!(fs::set_permissions(&out, attr.permissions()));
2807 fn copy_file_preserves_streams() {
2809 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2810 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 0);
2811 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2812 let mut v = Vec::new();
2813 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2814 assert_eq!(v, b"carrot".to_vec());
2818 fn copy_file_returns_metadata_len() {
2820 let in_path = tmp.join("in.txt");
2821 let out_path = tmp.join("out.txt");
2822 check!(check!(File::create(&in_path)).write(b"lettuce"));
2824 check!(check!(File::create(tmp.join("in.txt:bunny"))).write(b"carrot"));
2825 let copied_len = check!(fs::copy(&in_path, &out_path));
2826 assert_eq!(check!(out_path.metadata()).len(), copied_len);
2830 fn symlinks_work() {
2831 let tmpdir = tmpdir();
2832 if !got_symlink_permission(&tmpdir) { return };
2834 let input = tmpdir.join("in.txt");
2835 let out = tmpdir.join("out.txt");
2837 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2838 check!(symlink_file(&input, &out));
2839 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
2840 assert_eq!(check!(fs::metadata(&out)).len(),
2841 check!(fs::metadata(&input)).len());
2842 let mut v = Vec::new();
2843 check!(check!(File::open(&out)).read_to_end(&mut v));
2844 assert_eq!(v, b"foobar".to_vec());
2848 fn symlink_noexist() {
2849 // Symlinks can point to things that don't exist
2850 let tmpdir = tmpdir();
2851 if !got_symlink_permission(&tmpdir) { return };
2853 // Use a relative path for testing. Symlinks get normalized by Windows,
2854 // so we may not get the same path back for absolute paths
2855 check!(symlink_file(&"foo", &tmpdir.join("bar")));
2856 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(),
2863 // directory symlink
2864 assert_eq!(check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
2867 assert_eq!(check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
2868 r"C:\Users\Default");
2869 // junction with special permissions
2870 assert_eq!(check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
2873 let tmpdir = tmpdir();
2874 let link = tmpdir.join("link");
2875 if !got_symlink_permission(&tmpdir) { return };
2876 check!(symlink_file(&"foo", &link));
2877 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
2881 fn readlink_not_symlink() {
2882 let tmpdir = tmpdir();
2883 match fs::read_link(tmpdir.path()) {
2884 Ok(..) => panic!("wanted a failure"),
2891 let tmpdir = tmpdir();
2892 let input = tmpdir.join("in.txt");
2893 let out = tmpdir.join("out.txt");
2895 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2896 check!(fs::hard_link(&input, &out));
2897 assert_eq!(check!(fs::metadata(&out)).len(),
2898 check!(fs::metadata(&input)).len());
2899 assert_eq!(check!(fs::metadata(&out)).len(),
2900 check!(input.metadata()).len());
2901 let mut v = Vec::new();
2902 check!(check!(File::open(&out)).read_to_end(&mut v));
2903 assert_eq!(v, b"foobar".to_vec());
2905 // can't link to yourself
2906 match fs::hard_link(&input, &input) {
2907 Ok(..) => panic!("wanted a failure"),
2910 // can't link to something that doesn't exist
2911 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
2912 Ok(..) => panic!("wanted a failure"),
2919 let tmpdir = tmpdir();
2920 let file = tmpdir.join("in.txt");
2922 check!(File::create(&file));
2923 let attr = check!(fs::metadata(&file));
2924 assert!(!attr.permissions().readonly());
2925 let mut p = attr.permissions();
2926 p.set_readonly(true);
2927 check!(fs::set_permissions(&file, p.clone()));
2928 let attr = check!(fs::metadata(&file));
2929 assert!(attr.permissions().readonly());
2931 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
2932 Ok(..) => panic!("wanted an error"),
2936 p.set_readonly(false);
2937 check!(fs::set_permissions(&file, p));
2942 let tmpdir = tmpdir();
2943 let path = tmpdir.join("in.txt");
2945 let file = check!(File::create(&path));
2946 let attr = check!(fs::metadata(&path));
2947 assert!(!attr.permissions().readonly());
2948 let mut p = attr.permissions();
2949 p.set_readonly(true);
2950 check!(file.set_permissions(p.clone()));
2951 let attr = check!(fs::metadata(&path));
2952 assert!(attr.permissions().readonly());
2954 p.set_readonly(false);
2955 check!(file.set_permissions(p));
2959 fn sync_doesnt_kill_anything() {
2960 let tmpdir = tmpdir();
2961 let path = tmpdir.join("in.txt");
2963 let mut file = check!(File::create(&path));
2964 check!(file.sync_all());
2965 check!(file.sync_data());
2966 check!(file.write(b"foo"));
2967 check!(file.sync_all());
2968 check!(file.sync_data());
2972 fn truncate_works() {
2973 let tmpdir = tmpdir();
2974 let path = tmpdir.join("in.txt");
2976 let mut file = check!(File::create(&path));
2977 check!(file.write(b"foo"));
2978 check!(file.sync_all());
2980 // Do some simple things with truncation
2981 assert_eq!(check!(file.metadata()).len(), 3);
2982 check!(file.set_len(10));
2983 assert_eq!(check!(file.metadata()).len(), 10);
2984 check!(file.write(b"bar"));
2985 check!(file.sync_all());
2986 assert_eq!(check!(file.metadata()).len(), 10);
2988 let mut v = Vec::new();
2989 check!(check!(File::open(&path)).read_to_end(&mut v));
2990 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
2992 // Truncate to a smaller length, don't seek, and then write something.
2993 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
2994 // past the end of the file).
2995 check!(file.set_len(2));
2996 assert_eq!(check!(file.metadata()).len(), 2);
2997 check!(file.write(b"wut"));
2998 check!(file.sync_all());
2999 assert_eq!(check!(file.metadata()).len(), 9);
3000 let mut v = Vec::new();
3001 check!(check!(File::open(&path)).read_to_end(&mut v));
3002 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
3007 use fs::OpenOptions as OO;
3008 fn c<T: Clone>(t: &T) -> T { t.clone() }
3010 let tmpdir = tmpdir();
3012 let mut r = OO::new(); r.read(true);
3013 let mut w = OO::new(); w.write(true);
3014 let mut rw = OO::new(); rw.read(true).write(true);
3015 let mut a = OO::new(); a.append(true);
3016 let mut ra = OO::new(); ra.read(true).append(true);
3019 let invalid_options = 87; // ERROR_INVALID_PARAMETER
3021 let invalid_options = "Invalid argument";
3023 // Test various combinations of creation modes and access modes.
3026 // creation mode | read | write | read-write | append | read-append |
3027 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
3028 // not set (open existing) | X | X | X | X | X |
3029 // create | | X | X | X | X |
3030 // truncate | | X | X | | |
3031 // create and truncate | | X | X | | |
3032 // create_new | | X | X | X | X |
3034 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
3037 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
3038 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
3039 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
3040 check!(c(&w).create(true).open(&tmpdir.join("a")));
3041 check!(c(&w).open(&tmpdir.join("a")));
3044 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
3045 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
3046 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
3047 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
3048 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
3051 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
3052 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
3053 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
3054 check!(c(&rw).create(true).open(&tmpdir.join("c")));
3055 check!(c(&rw).open(&tmpdir.join("c")));
3058 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
3059 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
3060 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
3061 check!(c(&a).create(true).open(&tmpdir.join("d")));
3062 check!(c(&a).open(&tmpdir.join("d")));
3065 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
3066 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
3067 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
3068 check!(c(&ra).create(true).open(&tmpdir.join("e")));
3069 check!(c(&ra).open(&tmpdir.join("e")));
3071 // Test opening a file without setting an access mode
3072 let mut blank = OO::new();
3073 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
3076 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
3078 // Test write fails for read-only
3079 check!(r.open(&tmpdir.join("h")));
3081 let mut f = check!(r.open(&tmpdir.join("h")));
3082 assert!(f.write("wut".as_bytes()).is_err());
3085 // Test write overwrites
3087 let mut f = check!(c(&w).open(&tmpdir.join("h")));
3088 check!(f.write("baz".as_bytes()));
3091 let mut f = check!(c(&r).open(&tmpdir.join("h")));
3092 let mut b = vec![0; 6];
3093 check!(f.read(&mut b));
3094 assert_eq!(b, "bazbar".as_bytes());
3097 // Test truncate works
3099 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
3100 check!(f.write("foo".as_bytes()));
3102 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3104 // Test append works
3105 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3107 let mut f = check!(c(&a).open(&tmpdir.join("h")));
3108 check!(f.write("bar".as_bytes()));
3110 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
3112 // Test .append(true) equals .write(true).append(true)
3114 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
3115 check!(f.write("baz".as_bytes()));
3117 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
3121 fn _assert_send_sync() {
3122 fn _assert_send_sync<T: Send + Sync>() {}
3123 _assert_send_sync::<OpenOptions>();
3128 let mut bytes = [0; 1024];
3129 StdRng::from_entropy().fill_bytes(&mut bytes);
3131 let tmpdir = tmpdir();
3133 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
3134 let mut v = Vec::new();
3135 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
3136 assert!(v == &bytes[..]);
3140 fn write_then_read() {
3141 let mut bytes = [0; 1024];
3142 StdRng::from_entropy().fill_bytes(&mut bytes);
3144 let tmpdir = tmpdir();
3146 check!(fs::write(&tmpdir.join("test"), &bytes[..]));
3147 let v = check!(fs::read(&tmpdir.join("test")));
3148 assert!(v == &bytes[..]);
3150 check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF]));
3151 error_contains!(fs::read_to_string(&tmpdir.join("not-utf8")),
3152 "stream did not contain valid UTF-8");
3155 check!(fs::write(&tmpdir.join("utf8"), s.as_bytes()));
3156 let string = check!(fs::read_to_string(&tmpdir.join("utf8")));
3157 assert_eq!(string, s);
3161 fn file_try_clone() {
3162 let tmpdir = tmpdir();
3164 let mut f1 = check!(OpenOptions::new()
3168 .open(&tmpdir.join("test")));
3169 let mut f2 = check!(f1.try_clone());
3171 check!(f1.write_all(b"hello world"));
3172 check!(f1.seek(SeekFrom::Start(2)));
3174 let mut buf = vec![];
3175 check!(f2.read_to_end(&mut buf));
3176 assert_eq!(buf, b"llo world");
3179 check!(f1.write_all(b"!"));
3183 #[cfg(not(windows))]
3184 fn unlink_readonly() {
3185 let tmpdir = tmpdir();
3186 let path = tmpdir.join("file");
3187 check!(File::create(&path));
3188 let mut perm = check!(fs::metadata(&path)).permissions();
3189 perm.set_readonly(true);
3190 check!(fs::set_permissions(&path, perm));
3191 check!(fs::remove_file(&path));
3195 fn mkdir_trailing_slash() {
3196 let tmpdir = tmpdir();
3197 let path = tmpdir.join("file");
3198 check!(fs::create_dir_all(&path.join("a/")));
3202 fn canonicalize_works_simple() {
3203 let tmpdir = tmpdir();
3204 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3205 let file = tmpdir.join("test");
3206 File::create(&file).unwrap();
3207 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3211 fn realpath_works() {
3212 let tmpdir = tmpdir();
3213 if !got_symlink_permission(&tmpdir) { return };
3215 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3216 let file = tmpdir.join("test");
3217 let dir = tmpdir.join("test2");
3218 let link = dir.join("link");
3219 let linkdir = tmpdir.join("test3");
3221 File::create(&file).unwrap();
3222 fs::create_dir(&dir).unwrap();
3223 symlink_file(&file, &link).unwrap();
3224 symlink_dir(&dir, &linkdir).unwrap();
3226 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
3228 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
3229 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3230 assert_eq!(fs::canonicalize(&link).unwrap(), file);
3231 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
3232 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
3236 fn realpath_works_tricky() {
3237 let tmpdir = tmpdir();
3238 if !got_symlink_permission(&tmpdir) { return };
3240 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3241 let a = tmpdir.join("a");
3242 let b = a.join("b");
3243 let c = b.join("c");
3244 let d = a.join("d");
3245 let e = d.join("e");
3246 let f = a.join("f");
3248 fs::create_dir_all(&b).unwrap();
3249 fs::create_dir_all(&d).unwrap();
3250 File::create(&f).unwrap();
3251 if cfg!(not(windows)) {
3252 symlink_dir("../d/e", &c).unwrap();
3253 symlink_file("../f", &e).unwrap();
3256 symlink_dir(r"..\d\e", &c).unwrap();
3257 symlink_file(r"..\f", &e).unwrap();
3260 assert_eq!(fs::canonicalize(&c).unwrap(), f);
3261 assert_eq!(fs::canonicalize(&e).unwrap(), f);
3265 fn dir_entry_methods() {
3266 let tmpdir = tmpdir();
3268 fs::create_dir_all(&tmpdir.join("a")).unwrap();
3269 File::create(&tmpdir.join("b")).unwrap();
3271 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
3272 let fname = file.file_name();
3273 match fname.to_str() {
3275 assert!(file.file_type().unwrap().is_dir());
3276 assert!(file.metadata().unwrap().is_dir());
3279 assert!(file.file_type().unwrap().is_file());
3280 assert!(file.metadata().unwrap().is_file());
3282 f => panic!("unknown file name: {:?}", f),
3288 fn dir_entry_debug() {
3289 let tmpdir = tmpdir();
3290 File::create(&tmpdir.join("b")).unwrap();
3291 let mut read_dir = tmpdir.path().read_dir().unwrap();
3292 let dir_entry = read_dir.next().unwrap().unwrap();
3293 let actual = format!("{:?}", dir_entry);
3294 let expected = format!("DirEntry({:?})", dir_entry.0.path());
3295 assert_eq!(actual, expected);
3299 fn read_dir_not_found() {
3300 let res = fs::read_dir("/path/that/does/not/exist");
3301 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
3305 fn create_dir_all_with_junctions() {
3306 let tmpdir = tmpdir();
3307 let target = tmpdir.join("target");
3309 let junction = tmpdir.join("junction");
3310 let b = junction.join("a/b");
3312 let link = tmpdir.join("link");
3313 let d = link.join("c/d");
3315 fs::create_dir(&target).unwrap();
3317 check!(symlink_junction(&target, &junction));
3318 check!(fs::create_dir_all(&b));
3319 // the junction itself is not a directory, but `is_dir()` on a Path
3321 assert!(junction.is_dir());
3322 assert!(b.exists());
3324 if !got_symlink_permission(&tmpdir) { return };
3325 check!(symlink_dir(&target, &link));
3326 check!(fs::create_dir_all(&d));
3327 assert!(link.is_dir());
3328 assert!(d.exists());
3332 fn metadata_access_times() {
3333 let tmpdir = tmpdir();
3335 let b = tmpdir.join("b");
3336 File::create(&b).unwrap();
3338 let a = check!(fs::metadata(&tmpdir.path()));
3339 let b = check!(fs::metadata(&b));
3341 assert_eq!(check!(a.accessed()), check!(a.accessed()));
3342 assert_eq!(check!(a.modified()), check!(a.modified()));
3343 assert_eq!(check!(b.accessed()), check!(b.modified()));
3345 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3346 check!(a.created());
3347 check!(b.created());