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 /// Creates 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 fn inner(path: &Path) -> io::Result<Vec<u8>> {
258 let mut file = File::open(path)?;
259 let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
260 file.read_to_end(&mut bytes)?;
266 /// Read the entire contents of a file into a string.
268 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
269 /// with fewer imports and without an intermediate variable. It pre-allocates a
270 /// buffer based on the file size when available, so it is generally faster than
271 /// reading into a string created with `String::new()`.
273 /// [`File::open`]: struct.File.html#method.open
274 /// [`read_to_string`]: ../io/trait.Read.html#method.read_to_string
278 /// This function will return an error if `path` does not already exist.
279 /// Other errors may also be returned according to [`OpenOptions::open`].
281 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
283 /// It will also return an error if it encounters while reading an error
284 /// of a kind other than [`ErrorKind::Interrupted`],
285 /// or if the contents of the file are not valid UTF-8.
287 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
293 /// use std::net::SocketAddr;
295 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
296 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
300 #[stable(feature = "fs_read_write", since = "1.26.0")]
301 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
302 fn inner(path: &Path) -> io::Result<String> {
303 let mut file = File::open(path)?;
304 let mut string = String::with_capacity(initial_buffer_size(&file));
305 file.read_to_string(&mut string)?;
311 /// Write a slice as the entire contents of a file.
313 /// This function will create a file if it does not exist,
314 /// and will entirely replace its contents if it does.
316 /// This is a convenience function for using [`File::create`] and [`write_all`]
317 /// with fewer imports.
319 /// [`File::create`]: struct.File.html#method.create
320 /// [`write_all`]: ../io/trait.Write.html#method.write_all
327 /// fn main() -> std::io::Result<()> {
328 /// fs::write("foo.txt", b"Lorem ipsum")?;
329 /// fs::write("bar.txt", "dolor sit")?;
333 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
334 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
335 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
336 File::create(path)?.write_all(contents)
338 inner(path.as_ref(), contents.as_ref())
342 /// Attempts to open a file in read-only mode.
344 /// See the [`OpenOptions::open`] method for more details.
348 /// This function will return an error if `path` does not already exist.
349 /// Other errors may also be returned according to [`OpenOptions::open`].
351 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
356 /// use std::fs::File;
358 /// fn main() -> std::io::Result<()> {
359 /// let mut f = File::open("foo.txt")?;
363 #[stable(feature = "rust1", since = "1.0.0")]
364 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
365 OpenOptions::new().read(true).open(path.as_ref())
368 /// Opens a file in write-only mode.
370 /// This function will create a file if it does not exist,
371 /// and will truncate it if it does.
373 /// See the [`OpenOptions::open`] function for more details.
375 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
380 /// use std::fs::File;
382 /// fn main() -> std::io::Result<()> {
383 /// let mut f = File::create("foo.txt")?;
387 #[stable(feature = "rust1", since = "1.0.0")]
388 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
389 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
392 /// Attempts to sync all OS-internal metadata to disk.
394 /// This function will attempt to ensure that all in-core data reaches the
395 /// filesystem before returning.
400 /// use std::fs::File;
401 /// use std::io::prelude::*;
403 /// fn main() -> std::io::Result<()> {
404 /// let mut f = File::create("foo.txt")?;
405 /// f.write_all(b"Hello, world!")?;
411 #[stable(feature = "rust1", since = "1.0.0")]
412 pub fn sync_all(&self) -> io::Result<()> {
416 /// This function is similar to [`sync_all`], except that it may not
417 /// synchronize file metadata to the filesystem.
419 /// This is intended for use cases that must synchronize content, but don't
420 /// need the metadata on disk. The goal of this method is to reduce disk
423 /// Note that some platforms may simply implement this in terms of
426 /// [`sync_all`]: struct.File.html#method.sync_all
431 /// use std::fs::File;
432 /// use std::io::prelude::*;
434 /// fn main() -> std::io::Result<()> {
435 /// let mut f = File::create("foo.txt")?;
436 /// f.write_all(b"Hello, world!")?;
442 #[stable(feature = "rust1", since = "1.0.0")]
443 pub fn sync_data(&self) -> io::Result<()> {
444 self.inner.datasync()
447 /// Truncates or extends the underlying file, updating the size of
448 /// this file to become `size`.
450 /// If the `size` is less than the current file's size, then the file will
451 /// be shrunk. If it is greater than the current file's size, then the file
452 /// will be extended to `size` and have all of the intermediate data filled
455 /// The file's cursor isn't changed. In particular, if the cursor was at the
456 /// end and the file is shrunk using this operation, the cursor will now be
461 /// This function will return an error if the file is not opened for writing.
466 /// use std::fs::File;
468 /// fn main() -> std::io::Result<()> {
469 /// let mut f = File::create("foo.txt")?;
475 /// Note that this method alters the content of the underlying file, even
476 /// though it takes `&self` rather than `&mut self`.
477 #[stable(feature = "rust1", since = "1.0.0")]
478 pub fn set_len(&self, size: u64) -> io::Result<()> {
479 self.inner.truncate(size)
482 /// Queries metadata about the underlying file.
487 /// use std::fs::File;
489 /// fn main() -> std::io::Result<()> {
490 /// let mut f = File::open("foo.txt")?;
491 /// let metadata = f.metadata()?;
495 #[stable(feature = "rust1", since = "1.0.0")]
496 pub fn metadata(&self) -> io::Result<Metadata> {
497 self.inner.file_attr().map(Metadata)
500 /// Creates a new `File` instance that shares the same underlying file handle
501 /// as the existing `File` instance. Reads, writes, and seeks will affect
502 /// both `File` instances simultaneously.
506 /// Creates two handles for a file named `foo.txt`:
509 /// use std::fs::File;
511 /// fn main() -> std::io::Result<()> {
512 /// let mut file = File::open("foo.txt")?;
513 /// let file_copy = file.try_clone()?;
518 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
519 /// two handles, seek one of them, and read the remaining bytes from the
523 /// use std::fs::File;
524 /// use std::io::SeekFrom;
525 /// use std::io::prelude::*;
527 /// fn main() -> std::io::Result<()> {
528 /// let mut file = File::open("foo.txt")?;
529 /// let mut file_copy = file.try_clone()?;
531 /// file.seek(SeekFrom::Start(3))?;
533 /// let mut contents = vec![];
534 /// file_copy.read_to_end(&mut contents)?;
535 /// assert_eq!(contents, b"def\n");
539 #[stable(feature = "file_try_clone", since = "1.9.0")]
540 pub fn try_clone(&self) -> io::Result<File> {
542 inner: self.inner.duplicate()?
546 /// Changes the permissions on the underlying file.
548 /// # Platform-specific behavior
550 /// This function currently corresponds to the `fchmod` function on Unix and
551 /// the `SetFileInformationByHandle` function on Windows. Note that, this
552 /// [may change in the future][changes].
554 /// [changes]: ../io/index.html#platform-specific-behavior
558 /// This function will return an error if the user lacks permission change
559 /// attributes on the underlying file. It may also return an error in other
560 /// os-specific unspecified cases.
565 /// fn main() -> std::io::Result<()> {
566 /// use std::fs::File;
568 /// let file = File::open("foo.txt")?;
569 /// let mut perms = file.metadata()?.permissions();
570 /// perms.set_readonly(true);
571 /// file.set_permissions(perms)?;
576 /// Note that this method alters the permissions of the underlying file,
577 /// even though it takes `&self` rather than `&mut self`.
578 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
579 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
580 self.inner.set_permissions(perm.0)
584 impl AsInner<fs_imp::File> for File {
585 fn as_inner(&self) -> &fs_imp::File { &self.inner }
587 impl FromInner<fs_imp::File> for File {
588 fn from_inner(f: fs_imp::File) -> File {
592 impl IntoInner<fs_imp::File> for File {
593 fn into_inner(self) -> fs_imp::File {
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl fmt::Debug for File {
600 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
605 #[stable(feature = "rust1", since = "1.0.0")]
607 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
612 unsafe fn initializer(&self) -> Initializer {
616 #[stable(feature = "rust1", since = "1.0.0")]
617 impl Write for File {
618 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
619 self.inner.write(buf)
621 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
623 #[stable(feature = "rust1", since = "1.0.0")]
625 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl Read for &File {
631 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
636 unsafe fn initializer(&self) -> Initializer {
640 #[stable(feature = "rust1", since = "1.0.0")]
641 impl Write for &File {
642 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
643 self.inner.write(buf)
645 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
647 #[stable(feature = "rust1", since = "1.0.0")]
648 impl Seek for &File {
649 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
655 /// Creates a blank new set of options ready for configuration.
657 /// All options are initially set to `false`.
662 /// use std::fs::OpenOptions;
664 /// let mut options = OpenOptions::new();
665 /// let file = options.read(true).open("foo.txt");
667 #[stable(feature = "rust1", since = "1.0.0")]
668 pub fn new() -> OpenOptions {
669 OpenOptions(fs_imp::OpenOptions::new())
672 /// Sets the option for read access.
674 /// This option, when true, will indicate that the file should be
675 /// `read`-able if opened.
680 /// use std::fs::OpenOptions;
682 /// let file = OpenOptions::new().read(true).open("foo.txt");
684 #[stable(feature = "rust1", since = "1.0.0")]
685 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
686 self.0.read(read); self
689 /// Sets the option for write access.
691 /// This option, when true, will indicate that the file should be
692 /// `write`-able if opened.
694 /// If the file already exists, any write calls on it will overwrite its
695 /// contents, without truncating it.
700 /// use std::fs::OpenOptions;
702 /// let file = OpenOptions::new().write(true).open("foo.txt");
704 #[stable(feature = "rust1", since = "1.0.0")]
705 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
706 self.0.write(write); self
709 /// Sets the option for the append mode.
711 /// This option, when true, means that writes will append to a file instead
712 /// of overwriting previous contents.
713 /// Note that setting `.write(true).append(true)` has the same effect as
714 /// setting only `.append(true)`.
716 /// For most filesystems, the operating system guarantees that all writes are
717 /// atomic: no writes get mangled because another process writes at the same
720 /// One maybe obvious note when using append-mode: make sure that all data
721 /// that belongs together is written to the file in one operation. This
722 /// can be done by concatenating strings before passing them to [`write()`],
723 /// or using a buffered writer (with a buffer of adequate size),
724 /// and calling [`flush()`] when the message is complete.
726 /// If a file is opened with both read and append access, beware that after
727 /// opening, and after every write, the position for reading may be set at the
728 /// end of the file. So, before writing, save the current position (using
729 /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`), and restore it before the next read.
733 /// This function doesn't create the file if it doesn't exist. Use the [`create`]
736 /// [`write()`]: ../../std/fs/struct.File.html#method.write
737 /// [`flush()`]: ../../std/fs/struct.File.html#method.flush
738 /// [`seek`]: ../../std/fs/struct.File.html#method.seek
739 /// [`SeekFrom`]: ../../std/io/enum.SeekFrom.html
740 /// [`Current`]: ../../std/io/enum.SeekFrom.html#variant.Current
741 /// [`create`]: #method.create
746 /// use std::fs::OpenOptions;
748 /// let file = OpenOptions::new().append(true).open("foo.txt");
750 #[stable(feature = "rust1", since = "1.0.0")]
751 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
752 self.0.append(append); self
755 /// Sets the option for truncating a previous file.
757 /// If a file is successfully opened with this option set it will truncate
758 /// the file to 0 length if it already exists.
760 /// The file must be opened with write access for truncate to work.
765 /// use std::fs::OpenOptions;
767 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
769 #[stable(feature = "rust1", since = "1.0.0")]
770 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
771 self.0.truncate(truncate); self
774 /// Sets the option for creating a new file.
776 /// This option indicates whether a new file will be created if the file
777 /// does not yet already exist.
779 /// In order for the file to be created, [`write`] or [`append`] access must
782 /// [`write`]: #method.write
783 /// [`append`]: #method.append
788 /// use std::fs::OpenOptions;
790 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
792 #[stable(feature = "rust1", since = "1.0.0")]
793 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
794 self.0.create(create); self
797 /// Sets the option to always create a new file.
799 /// This option indicates whether a new file will be created.
800 /// No file is allowed to exist at the target location, also no (dangling)
803 /// This option is useful because it is atomic. Otherwise between checking
804 /// whether a file exists and creating a new one, the file may have been
805 /// created by another process (a TOCTOU race condition / attack).
807 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
810 /// The file must be opened with write or append access in order to create
813 /// [`.create()`]: #method.create
814 /// [`.truncate()`]: #method.truncate
819 /// use std::fs::OpenOptions;
821 /// let file = OpenOptions::new().write(true)
822 /// .create_new(true)
823 /// .open("foo.txt");
825 #[stable(feature = "expand_open_options2", since = "1.9.0")]
826 pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
827 self.0.create_new(create_new); self
830 /// Opens a file at `path` with the options specified by `self`.
834 /// This function will return an error under a number of different
835 /// circumstances. Some of these error conditions are listed here, together
836 /// with their [`ErrorKind`]. The mapping to [`ErrorKind`]s is not part of
837 /// the compatibility contract of the function, especially the `Other` kind
838 /// might change to more specific kinds in the future.
840 /// * [`NotFound`]: The specified file does not exist and neither `create`
841 /// or `create_new` is set.
842 /// * [`NotFound`]: One of the directory components of the file path does
844 /// * [`PermissionDenied`]: The user lacks permission to get the specified
845 /// access rights for the file.
846 /// * [`PermissionDenied`]: The user lacks permission to open one of the
847 /// directory components of the specified path.
848 /// * [`AlreadyExists`]: `create_new` was specified and the file already
850 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
851 /// without write access, no access mode set, etc.).
852 /// * [`Other`]: One of the directory components of the specified file path
853 /// was not, in fact, a directory.
854 /// * [`Other`]: Filesystem-level errors: full disk, write permission
855 /// requested on a read-only file system, exceeded disk quota, too many
856 /// open files, too long filename, too many symbolic links in the
857 /// specified path (Unix-like systems only), etc.
862 /// use std::fs::OpenOptions;
864 /// let file = OpenOptions::new().open("foo.txt");
867 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
868 /// [`AlreadyExists`]: ../io/enum.ErrorKind.html#variant.AlreadyExists
869 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
870 /// [`NotFound`]: ../io/enum.ErrorKind.html#variant.NotFound
871 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
872 /// [`PermissionDenied`]: ../io/enum.ErrorKind.html#variant.PermissionDenied
873 #[stable(feature = "rust1", since = "1.0.0")]
874 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
875 self._open(path.as_ref())
878 fn _open(&self, path: &Path) -> io::Result<File> {
879 let inner = fs_imp::File::open(path, &self.0)?;
884 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
885 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
889 /// Returns the file type for this metadata.
894 /// fn main() -> std::io::Result<()> {
897 /// let metadata = fs::metadata("foo.txt")?;
899 /// println!("{:?}", metadata.file_type());
903 #[stable(feature = "file_type", since = "1.1.0")]
904 pub fn file_type(&self) -> FileType {
905 FileType(self.0.file_type())
908 /// Returns `true` if this metadata is for a directory. The
909 /// result is mutually exclusive to the result of
910 /// [`is_file`], and will be false for symlink metadata
911 /// obtained from [`symlink_metadata`].
913 /// [`is_file`]: struct.Metadata.html#method.is_file
914 /// [`symlink_metadata`]: fn.symlink_metadata.html
919 /// fn main() -> std::io::Result<()> {
922 /// let metadata = fs::metadata("foo.txt")?;
924 /// assert!(!metadata.is_dir());
928 #[stable(feature = "rust1", since = "1.0.0")]
929 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
931 /// Returns `true` if this metadata is for a regular file. The
932 /// result is mutually exclusive to the result of
933 /// [`is_dir`], and will be false for symlink metadata
934 /// obtained from [`symlink_metadata`].
936 /// [`is_dir`]: struct.Metadata.html#method.is_dir
937 /// [`symlink_metadata`]: fn.symlink_metadata.html
944 /// fn main() -> std::io::Result<()> {
945 /// let metadata = fs::metadata("foo.txt")?;
947 /// assert!(metadata.is_file());
951 #[stable(feature = "rust1", since = "1.0.0")]
952 pub fn is_file(&self) -> bool { self.file_type().is_file() }
954 /// Returns the size of the file, in bytes, this metadata is for.
961 /// fn main() -> std::io::Result<()> {
962 /// let metadata = fs::metadata("foo.txt")?;
964 /// assert_eq!(0, metadata.len());
968 #[stable(feature = "rust1", since = "1.0.0")]
969 pub fn len(&self) -> u64 { self.0.size() }
971 /// Returns the permissions of the file this metadata is for.
978 /// fn main() -> std::io::Result<()> {
979 /// let metadata = fs::metadata("foo.txt")?;
981 /// assert!(!metadata.permissions().readonly());
985 #[stable(feature = "rust1", since = "1.0.0")]
986 pub fn permissions(&self) -> Permissions {
987 Permissions(self.0.perm())
990 /// Returns the last modification time listed in this metadata.
992 /// The returned value corresponds to the `mtime` field of `stat` on Unix
993 /// platforms and the `ftLastWriteTime` field on Windows platforms.
997 /// This field may not be available on all platforms, and will return an
998 /// `Err` on platforms where it is not available.
1005 /// fn main() -> std::io::Result<()> {
1006 /// let metadata = fs::metadata("foo.txt")?;
1008 /// if let Ok(time) = metadata.modified() {
1009 /// println!("{:?}", time);
1011 /// println!("Not supported on this platform");
1016 #[stable(feature = "fs_time", since = "1.10.0")]
1017 pub fn modified(&self) -> io::Result<SystemTime> {
1018 self.0.modified().map(FromInner::from_inner)
1021 /// Returns the last access time of this metadata.
1023 /// The returned value corresponds to the `atime` field of `stat` on Unix
1024 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1026 /// Note that not all platforms will keep this field update in a file's
1027 /// metadata, for example Windows has an option to disable updating this
1028 /// time when files are accessed and Linux similarly has `noatime`.
1032 /// This field may not be available on all platforms, and will return an
1033 /// `Err` on platforms where it is not available.
1040 /// fn main() -> std::io::Result<()> {
1041 /// let metadata = fs::metadata("foo.txt")?;
1043 /// if let Ok(time) = metadata.accessed() {
1044 /// println!("{:?}", time);
1046 /// println!("Not supported on this platform");
1051 #[stable(feature = "fs_time", since = "1.10.0")]
1052 pub fn accessed(&self) -> io::Result<SystemTime> {
1053 self.0.accessed().map(FromInner::from_inner)
1056 /// Returns the creation time listed in this metadata.
1058 /// The returned value corresponds to the `birthtime` field of `stat` on
1059 /// Unix platforms and the `ftCreationTime` field on Windows platforms.
1063 /// This field may not be available on all platforms, and will return an
1064 /// `Err` on platforms where it is not available.
1071 /// fn main() -> std::io::Result<()> {
1072 /// let metadata = fs::metadata("foo.txt")?;
1074 /// if let Ok(time) = metadata.created() {
1075 /// println!("{:?}", time);
1077 /// println!("Not supported on this platform");
1082 #[stable(feature = "fs_time", since = "1.10.0")]
1083 pub fn created(&self) -> io::Result<SystemTime> {
1084 self.0.created().map(FromInner::from_inner)
1088 #[stable(feature = "std_debug", since = "1.16.0")]
1089 impl fmt::Debug for Metadata {
1090 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1091 f.debug_struct("Metadata")
1092 .field("file_type", &self.file_type())
1093 .field("is_dir", &self.is_dir())
1094 .field("is_file", &self.is_file())
1095 .field("permissions", &self.permissions())
1096 .field("modified", &self.modified())
1097 .field("accessed", &self.accessed())
1098 .field("created", &self.created())
1103 impl AsInner<fs_imp::FileAttr> for Metadata {
1104 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
1108 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1113 /// use std::fs::File;
1115 /// fn main() -> std::io::Result<()> {
1116 /// let mut f = File::create("foo.txt")?;
1117 /// let metadata = f.metadata()?;
1119 /// assert_eq!(false, metadata.permissions().readonly());
1123 #[stable(feature = "rust1", since = "1.0.0")]
1124 pub fn readonly(&self) -> bool { self.0.readonly() }
1126 /// Modifies the readonly flag for this set of permissions. If the
1127 /// `readonly` argument is `true`, using the resulting `Permission` will
1128 /// update file permissions to forbid writing. Conversely, if it's `false`,
1129 /// using the resulting `Permission` will update file permissions to allow
1132 /// This operation does **not** modify the filesystem. To modify the
1133 /// filesystem use the [`fs::set_permissions`] function.
1135 /// [`fs::set_permissions`]: fn.set_permissions.html
1140 /// use std::fs::File;
1142 /// fn main() -> std::io::Result<()> {
1143 /// let f = File::create("foo.txt")?;
1144 /// let metadata = f.metadata()?;
1145 /// let mut permissions = metadata.permissions();
1147 /// permissions.set_readonly(true);
1149 /// // filesystem doesn't change
1150 /// assert_eq!(false, metadata.permissions().readonly());
1152 /// // just this particular `permissions`.
1153 /// assert_eq!(true, permissions.readonly());
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 pub fn set_readonly(&mut self, readonly: bool) {
1159 self.0.set_readonly(readonly)
1164 /// Tests whether this file type represents a directory. The
1165 /// result is mutually exclusive to the results of
1166 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1169 /// [`is_file`]: struct.FileType.html#method.is_file
1170 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1175 /// fn main() -> std::io::Result<()> {
1178 /// let metadata = fs::metadata("foo.txt")?;
1179 /// let file_type = metadata.file_type();
1181 /// assert_eq!(file_type.is_dir(), false);
1185 #[stable(feature = "file_type", since = "1.1.0")]
1186 pub fn is_dir(&self) -> bool { self.0.is_dir() }
1188 /// Tests whether this file type represents a regular file.
1189 /// The result is mutually exclusive to the results of
1190 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1193 /// [`is_dir`]: struct.FileType.html#method.is_dir
1194 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1199 /// fn main() -> std::io::Result<()> {
1202 /// let metadata = fs::metadata("foo.txt")?;
1203 /// let file_type = metadata.file_type();
1205 /// assert_eq!(file_type.is_file(), true);
1209 #[stable(feature = "file_type", since = "1.1.0")]
1210 pub fn is_file(&self) -> bool { self.0.is_file() }
1212 /// Tests whether this file type represents a symbolic link.
1213 /// The result is mutually exclusive to the results of
1214 /// [`is_dir`] and [`is_file`]; only zero or one of these
1217 /// The underlying [`Metadata`] struct needs to be retrieved
1218 /// with the [`fs::symlink_metadata`] function and not the
1219 /// [`fs::metadata`] function. The [`fs::metadata`] function
1220 /// follows symbolic links, so [`is_symlink`] would always
1221 /// return `false` for the target file.
1223 /// [`Metadata`]: struct.Metadata.html
1224 /// [`fs::metadata`]: fn.metadata.html
1225 /// [`fs::symlink_metadata`]: fn.symlink_metadata.html
1226 /// [`is_dir`]: struct.FileType.html#method.is_dir
1227 /// [`is_file`]: struct.FileType.html#method.is_file
1228 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1235 /// fn main() -> std::io::Result<()> {
1236 /// let metadata = fs::symlink_metadata("foo.txt")?;
1237 /// let file_type = metadata.file_type();
1239 /// assert_eq!(file_type.is_symlink(), false);
1243 #[stable(feature = "file_type", since = "1.1.0")]
1244 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
1247 impl AsInner<fs_imp::FileType> for FileType {
1248 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
1251 impl FromInner<fs_imp::FilePermissions> for Permissions {
1252 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1257 impl AsInner<fs_imp::FilePermissions> for Permissions {
1258 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 impl Iterator for ReadDir {
1263 type Item = io::Result<DirEntry>;
1265 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1266 self.0.next().map(|entry| entry.map(DirEntry))
1271 /// Returns the full path to the file that this entry represents.
1273 /// The full path is created by joining the original path to `read_dir`
1274 /// with the filename of this entry.
1281 /// fn main() -> std::io::Result<()> {
1282 /// for entry in fs::read_dir(".")? {
1283 /// let dir = entry?;
1284 /// println!("{:?}", dir.path());
1290 /// This prints output like:
1293 /// "./whatever.txt"
1295 /// "./hello_world.rs"
1298 /// The exact text, of course, depends on what files you have in `.`.
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 pub fn path(&self) -> PathBuf { self.0.path() }
1302 /// Returns the metadata for the file that this entry points at.
1304 /// This function will not traverse symlinks if this entry points at a
1307 /// # Platform-specific behavior
1309 /// On Windows this function is cheap to call (no extra system calls
1310 /// needed), but on Unix platforms this function is the equivalent of
1311 /// calling `symlink_metadata` on the path.
1318 /// if let Ok(entries) = fs::read_dir(".") {
1319 /// for entry in entries {
1320 /// if let Ok(entry) = entry {
1321 /// // Here, `entry` is a `DirEntry`.
1322 /// if let Ok(metadata) = entry.metadata() {
1323 /// // Now let's show our entry's permissions!
1324 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1326 /// println!("Couldn't get metadata for {:?}", entry.path());
1332 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1333 pub fn metadata(&self) -> io::Result<Metadata> {
1334 self.0.metadata().map(Metadata)
1337 /// Returns the file type for the file that this entry points at.
1339 /// This function will not traverse symlinks if this entry points at a
1342 /// # Platform-specific behavior
1344 /// On Windows and most Unix platforms this function is free (no extra
1345 /// system calls needed), but some Unix platforms may require the equivalent
1346 /// call to `symlink_metadata` to learn about the target file type.
1353 /// if let Ok(entries) = fs::read_dir(".") {
1354 /// for entry in entries {
1355 /// if let Ok(entry) = entry {
1356 /// // Here, `entry` is a `DirEntry`.
1357 /// if let Ok(file_type) = entry.file_type() {
1358 /// // Now let's show our entry's file type!
1359 /// println!("{:?}: {:?}", entry.path(), file_type);
1361 /// println!("Couldn't get file type for {:?}", entry.path());
1367 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1368 pub fn file_type(&self) -> io::Result<FileType> {
1369 self.0.file_type().map(FileType)
1372 /// Returns the bare file name of this directory entry without any other
1373 /// leading path component.
1380 /// if let Ok(entries) = fs::read_dir(".") {
1381 /// for entry in entries {
1382 /// if let Ok(entry) = entry {
1383 /// // Here, `entry` is a `DirEntry`.
1384 /// println!("{:?}", entry.file_name());
1389 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1390 pub fn file_name(&self) -> OsString {
1395 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1396 impl fmt::Debug for DirEntry {
1397 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1398 f.debug_tuple("DirEntry")
1399 .field(&self.path())
1404 impl AsInner<fs_imp::DirEntry> for DirEntry {
1405 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
1408 /// Removes a file from the filesystem.
1410 /// Note that there is no
1411 /// guarantee that the file is immediately deleted (e.g., depending on
1412 /// platform, other open file descriptors may prevent immediate removal).
1414 /// # Platform-specific behavior
1416 /// This function currently corresponds to the `unlink` function on Unix
1417 /// and the `DeleteFile` function on Windows.
1418 /// Note that, this [may change in the future][changes].
1420 /// [changes]: ../io/index.html#platform-specific-behavior
1424 /// This function will return an error in the following situations, but is not
1425 /// limited to just these cases:
1427 /// * `path` points to a directory.
1428 /// * The user lacks permissions to remove the file.
1435 /// fn main() -> std::io::Result<()> {
1436 /// fs::remove_file("a.txt")?;
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1442 fs_imp::unlink(path.as_ref())
1445 /// Given a path, query the file system to get information about a file,
1448 /// This function will traverse symbolic links to query information about the
1449 /// destination file.
1451 /// # Platform-specific behavior
1453 /// This function currently corresponds to the `stat` function on Unix
1454 /// and the `GetFileAttributesEx` function on Windows.
1455 /// Note that, this [may change in the future][changes].
1457 /// [changes]: ../io/index.html#platform-specific-behavior
1461 /// This function will return an error in the following situations, but is not
1462 /// limited to just these cases:
1464 /// * The user lacks permissions to perform `metadata` call on `path`.
1465 /// * `path` does not exist.
1472 /// fn main() -> std::io::Result<()> {
1473 /// let attr = fs::metadata("/some/file/path.txt")?;
1474 /// // inspect attr ...
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1480 fs_imp::stat(path.as_ref()).map(Metadata)
1483 /// Query the metadata about a file without following symlinks.
1485 /// # Platform-specific behavior
1487 /// This function currently corresponds to the `lstat` function on Unix
1488 /// and the `GetFileAttributesEx` function on Windows.
1489 /// Note that, this [may change in the future][changes].
1491 /// [changes]: ../io/index.html#platform-specific-behavior
1495 /// This function will return an error in the following situations, but is not
1496 /// limited to just these cases:
1498 /// * The user lacks permissions to perform `metadata` call on `path`.
1499 /// * `path` does not exist.
1506 /// fn main() -> std::io::Result<()> {
1507 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1508 /// // inspect attr ...
1512 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1513 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1514 fs_imp::lstat(path.as_ref()).map(Metadata)
1517 /// Rename a file or directory to a new name, replacing the original file if
1518 /// `to` already exists.
1520 /// This will not work if the new name is on a different mount point.
1522 /// # Platform-specific behavior
1524 /// This function currently corresponds to the `rename` function on Unix
1525 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1527 /// Because of this, the behavior when both `from` and `to` exist differs. On
1528 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1529 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1530 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1532 /// Note that, this [may change in the future][changes].
1534 /// [changes]: ../io/index.html#platform-specific-behavior
1538 /// This function will return an error in the following situations, but is not
1539 /// limited to just these cases:
1541 /// * `from` does not exist.
1542 /// * The user lacks permissions to view contents.
1543 /// * `from` and `to` are on separate filesystems.
1550 /// fn main() -> std::io::Result<()> {
1551 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1555 #[stable(feature = "rust1", since = "1.0.0")]
1556 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1557 fs_imp::rename(from.as_ref(), to.as_ref())
1560 /// Copies the contents of one file to another. This function will also
1561 /// copy the permission bits of the original file to the destination file.
1563 /// This function will **overwrite** the contents of `to`.
1565 /// Note that if `from` and `to` both point to the same file, then the file
1566 /// will likely get truncated by this operation.
1568 /// On success, the total number of bytes copied is returned and it is equal to
1569 /// the length of the `to` file as reported by `metadata`.
1571 /// If you’re wanting to copy the contents of one file to another and you’re
1572 /// working with [`File`]s, see the [`io::copy`] function.
1574 /// [`io::copy`]: ../io/fn.copy.html
1575 /// [`File`]: ./struct.File.html
1577 /// # Platform-specific behavior
1579 /// This function currently corresponds to the `open` function in Unix
1580 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1581 /// `O_CLOEXEC` is set for returned file descriptors.
1582 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1583 /// NTFS streams are copied but only the size of the main stream is returned by
1585 /// Note that, this [may change in the future][changes].
1587 /// [changes]: ../io/index.html#platform-specific-behavior
1591 /// This function will return an error in the following situations, but is not
1592 /// limited to just these cases:
1594 /// * The `from` path is not a file.
1595 /// * The `from` file does not exist.
1596 /// * The current process does not have the permission rights to access
1597 /// `from` or write `to`.
1604 /// fn main() -> std::io::Result<()> {
1605 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1609 #[stable(feature = "rust1", since = "1.0.0")]
1610 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1611 fs_imp::copy(from.as_ref(), to.as_ref())
1614 /// Creates a new hard link on the filesystem.
1616 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1617 /// often require these two paths to both be located on the same filesystem.
1619 /// # Platform-specific behavior
1621 /// This function currently corresponds to the `link` function on Unix
1622 /// and the `CreateHardLink` function on Windows.
1623 /// Note that, this [may change in the future][changes].
1625 /// [changes]: ../io/index.html#platform-specific-behavior
1629 /// This function will return an error in the following situations, but is not
1630 /// limited to just these cases:
1632 /// * The `src` path is not a file or doesn't exist.
1639 /// fn main() -> std::io::Result<()> {
1640 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1646 fs_imp::link(src.as_ref(), dst.as_ref())
1649 /// Creates a new symbolic link on the filesystem.
1651 /// The `dst` path will be a symbolic link pointing to the `src` path.
1652 /// On Windows, this will be a file symlink, not a directory symlink;
1653 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1654 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1655 /// used instead to make the intent explicit.
1657 /// [`std::os::unix::fs::symlink`]: ../os/unix/fs/fn.symlink.html
1658 /// [`std::os::windows::fs::symlink_file`]: ../os/windows/fs/fn.symlink_file.html
1659 /// [`symlink_dir`]: ../os/windows/fs/fn.symlink_dir.html
1667 /// fn main() -> std::io::Result<()> {
1668 /// fs::soft_link("a.txt", "b.txt")?;
1672 #[stable(feature = "rust1", since = "1.0.0")]
1673 #[rustc_deprecated(since = "1.1.0",
1674 reason = "replaced with std::os::unix::fs::symlink and \
1675 std::os::windows::fs::{symlink_file, symlink_dir}")]
1676 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1677 fs_imp::symlink(src.as_ref(), dst.as_ref())
1680 /// Reads a symbolic link, returning the file that the link points to.
1682 /// # Platform-specific behavior
1684 /// This function currently corresponds to the `readlink` function on Unix
1685 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1686 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1687 /// Note that, this [may change in the future][changes].
1689 /// [changes]: ../io/index.html#platform-specific-behavior
1693 /// This function will return an error in the following situations, but is not
1694 /// limited to just these cases:
1696 /// * `path` is not a symbolic link.
1697 /// * `path` does not exist.
1704 /// fn main() -> std::io::Result<()> {
1705 /// let path = fs::read_link("a.txt")?;
1709 #[stable(feature = "rust1", since = "1.0.0")]
1710 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1711 fs_imp::readlink(path.as_ref())
1714 /// Returns the canonical, absolute form of a path with all intermediate
1715 /// components normalized and symbolic links resolved.
1717 /// # Platform-specific behavior
1719 /// This function currently corresponds to the `realpath` function on Unix
1720 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1721 /// Note that, this [may change in the future][changes].
1723 /// On Windows, this converts the path to use [extended length path][path]
1724 /// syntax, which allows your program to use longer path names, but means you
1725 /// can only join backslash-delimited paths to it, and it may be incompatible
1726 /// with other applications (if passed to the application on the command-line,
1727 /// or written to a file another application may read).
1729 /// [changes]: ../io/index.html#platform-specific-behavior
1730 /// [path]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
1734 /// This function will return an error in the following situations, but is not
1735 /// limited to just these cases:
1737 /// * `path` does not exist.
1738 /// * A non-final component in path is not a directory.
1745 /// fn main() -> std::io::Result<()> {
1746 /// let path = fs::canonicalize("../a/../foo.txt")?;
1750 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1751 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1752 fs_imp::canonicalize(path.as_ref())
1755 /// Creates a new, empty directory at the provided path
1757 /// # Platform-specific behavior
1759 /// This function currently corresponds to the `mkdir` function on Unix
1760 /// and the `CreateDirectory` function on Windows.
1761 /// Note that, this [may change in the future][changes].
1763 /// [changes]: ../io/index.html#platform-specific-behavior
1765 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1766 /// return an error. To create a directory and all its missing parents at the
1767 /// same time, use the [`create_dir_all`] function.
1771 /// This function will return an error in the following situations, but is not
1772 /// limited to just these cases:
1774 /// * User lacks permissions to create directory at `path`.
1775 /// * A parent of the given path doesn't exist. (To create a directory and all
1776 /// its missing parents at the same time, use the [`create_dir_all`]
1778 /// * `path` already exists.
1785 /// fn main() -> std::io::Result<()> {
1786 /// fs::create_dir("/some/dir")?;
1790 #[stable(feature = "rust1", since = "1.0.0")]
1791 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1792 DirBuilder::new().create(path.as_ref())
1795 /// Recursively create a directory and all of its parent components if they
1798 /// # Platform-specific behavior
1800 /// This function currently corresponds to the `mkdir` function on Unix
1801 /// and the `CreateDirectory` function on Windows.
1802 /// Note that, this [may change in the future][changes].
1804 /// [changes]: ../io/index.html#platform-specific-behavior
1808 /// This function will return an error in the following situations, but is not
1809 /// limited to just these cases:
1811 /// * If any directory in the path specified by `path`
1812 /// does not already exist and it could not be created otherwise. The specific
1813 /// error conditions for when a directory is being created (after it is
1814 /// determined to not exist) are outlined by [`fs::create_dir`].
1816 /// Notable exception is made for situations where any of the directories
1817 /// specified in the `path` could not be created as it was being created concurrently.
1818 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1819 /// concurrently from multiple threads or processes is guaranteed not to fail
1820 /// due to a race condition with itself.
1822 /// [`fs::create_dir`]: fn.create_dir.html
1829 /// fn main() -> std::io::Result<()> {
1830 /// fs::create_dir_all("/some/dir")?;
1834 #[stable(feature = "rust1", since = "1.0.0")]
1835 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1836 DirBuilder::new().recursive(true).create(path.as_ref())
1839 /// Removes an existing, empty directory.
1841 /// # Platform-specific behavior
1843 /// This function currently corresponds to the `rmdir` function on Unix
1844 /// and the `RemoveDirectory` function on Windows.
1845 /// Note that, this [may change in the future][changes].
1847 /// [changes]: ../io/index.html#platform-specific-behavior
1851 /// This function will return an error in the following situations, but is not
1852 /// limited to just these cases:
1854 /// * The user lacks permissions to remove the directory at the provided `path`.
1855 /// * The directory isn't empty.
1862 /// fn main() -> std::io::Result<()> {
1863 /// fs::remove_dir("/some/dir")?;
1867 #[stable(feature = "rust1", since = "1.0.0")]
1868 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1869 fs_imp::rmdir(path.as_ref())
1872 /// Removes a directory at this path, after removing all its contents. Use
1875 /// This function does **not** follow symbolic links and it will simply remove the
1876 /// symbolic link itself.
1878 /// # Platform-specific behavior
1880 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1881 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1883 /// Note that, this [may change in the future][changes].
1885 /// [changes]: ../io/index.html#platform-specific-behavior
1889 /// See [`fs::remove_file`] and [`fs::remove_dir`].
1891 /// [`fs::remove_file`]: fn.remove_file.html
1892 /// [`fs::remove_dir`]: fn.remove_dir.html
1899 /// fn main() -> std::io::Result<()> {
1900 /// fs::remove_dir_all("/some/dir")?;
1904 #[stable(feature = "rust1", since = "1.0.0")]
1905 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1906 fs_imp::remove_dir_all(path.as_ref())
1909 /// Returns an iterator over the entries within a directory.
1911 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
1912 /// New errors may be encountered after an iterator is initially constructed.
1914 /// [`io::Result`]: ../io/type.Result.html
1915 /// [`DirEntry`]: struct.DirEntry.html
1917 /// # Platform-specific behavior
1919 /// This function currently corresponds to the `opendir` function on Unix
1920 /// and the `FindFirstFile` function on Windows.
1921 /// Note that, this [may change in the future][changes].
1923 /// [changes]: ../io/index.html#platform-specific-behavior
1927 /// This function will return an error in the following situations, but is not
1928 /// limited to just these cases:
1930 /// * The provided `path` doesn't exist.
1931 /// * The process lacks permissions to view the contents.
1932 /// * The `path` points at a non-directory file.
1938 /// use std::fs::{self, DirEntry};
1939 /// use std::path::Path;
1941 /// // one possible implementation of walking a directory only visiting files
1942 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1943 /// if dir.is_dir() {
1944 /// for entry in fs::read_dir(dir)? {
1945 /// let entry = entry?;
1946 /// let path = entry.path();
1947 /// if path.is_dir() {
1948 /// visit_dirs(&path, cb)?;
1957 #[stable(feature = "rust1", since = "1.0.0")]
1958 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1959 fs_imp::readdir(path.as_ref()).map(ReadDir)
1962 /// Changes the permissions found on a file or a directory.
1964 /// # Platform-specific behavior
1966 /// This function currently corresponds to the `chmod` function on Unix
1967 /// and the `SetFileAttributes` function on Windows.
1968 /// Note that, this [may change in the future][changes].
1970 /// [changes]: ../io/index.html#platform-specific-behavior
1974 /// This function will return an error in the following situations, but is not
1975 /// limited to just these cases:
1977 /// * `path` does not exist.
1978 /// * The user lacks the permission to change attributes of the file.
1985 /// fn main() -> std::io::Result<()> {
1986 /// let mut perms = fs::metadata("foo.txt")?.permissions();
1987 /// perms.set_readonly(true);
1988 /// fs::set_permissions("foo.txt", perms)?;
1992 #[stable(feature = "set_permissions", since = "1.1.0")]
1993 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
1995 fs_imp::set_perm(path.as_ref(), perm.0)
1999 /// Creates a new set of options with default mode/security settings for all
2000 /// platforms and also non-recursive.
2005 /// use std::fs::DirBuilder;
2007 /// let builder = DirBuilder::new();
2009 #[stable(feature = "dir_builder", since = "1.6.0")]
2010 pub fn new() -> DirBuilder {
2012 inner: fs_imp::DirBuilder::new(),
2017 /// Indicates that directories should be created recursively, creating all
2018 /// parent directories. Parents that do not exist are created with the same
2019 /// security and permissions settings.
2021 /// This option defaults to `false`.
2026 /// use std::fs::DirBuilder;
2028 /// let mut builder = DirBuilder::new();
2029 /// builder.recursive(true);
2031 #[stable(feature = "dir_builder", since = "1.6.0")]
2032 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2033 self.recursive = recursive;
2037 /// Creates the specified directory with the options configured in this
2040 /// It is considered an error if the directory already exists unless
2041 /// recursive mode is enabled.
2046 /// use std::fs::{self, DirBuilder};
2048 /// let path = "/tmp/foo/bar/baz";
2049 /// DirBuilder::new()
2050 /// .recursive(true)
2051 /// .create(path).unwrap();
2053 /// assert!(fs::metadata(path).unwrap().is_dir());
2055 #[stable(feature = "dir_builder", since = "1.6.0")]
2056 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2057 self._create(path.as_ref())
2060 fn _create(&self, path: &Path) -> io::Result<()> {
2062 self.create_dir_all(path)
2064 self.inner.mkdir(path)
2068 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2069 if path == Path::new("") {
2073 match self.inner.mkdir(path) {
2074 Ok(()) => return Ok(()),
2075 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2076 Err(_) if path.is_dir() => return Ok(()),
2077 Err(e) => return Err(e),
2079 match path.parent() {
2080 Some(p) => self.create_dir_all(p)?,
2081 None => return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree")),
2083 match self.inner.mkdir(path) {
2085 Err(_) if path.is_dir() => Ok(()),
2091 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2092 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2097 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
2101 use fs::{self, File, OpenOptions};
2102 use io::{ErrorKind, SeekFrom};
2104 use rand::{rngs::StdRng, FromEntropy, RngCore};
2106 use sys_common::io::test::{TempDir, tmpdir};
2110 use os::windows::fs::{symlink_dir, symlink_file};
2112 use sys::fs::symlink_junction;
2114 use os::unix::fs::symlink as symlink_dir;
2116 use os::unix::fs::symlink as symlink_file;
2118 use os::unix::fs::symlink as symlink_junction;
2120 macro_rules! check { ($e:expr) => (
2123 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
2128 macro_rules! error { ($e:expr, $s:expr) => (
2130 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2131 Err(ref err) => assert!(err.raw_os_error() == Some($s),
2132 format!("`{}` did not have a code of `{}`", err, $s))
2137 macro_rules! error { ($e:expr, $s:expr) => ( error_contains!($e, $s) ) }
2139 macro_rules! error_contains { ($e:expr, $s:expr) => (
2141 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2142 Err(ref err) => assert!(err.to_string().contains($s),
2143 format!("`{}` did not contain `{}`", err, $s))
2147 // Several test fail on windows if the user does not have permission to
2148 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
2149 // disabling these test on Windows, use this function to test whether we
2150 // have permission, and return otherwise. This way, we still don't run these
2151 // tests most of the time, but at least we do if the user has the right
2153 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
2154 if cfg!(unix) { return true }
2155 let link = tmpdir.join("some_hopefully_unique_link_name");
2157 match symlink_file(r"nonexisting_target", link) {
2159 // ERROR_PRIVILEGE_NOT_HELD = 1314
2160 Err(ref err) if err.raw_os_error() == Some(1314) => false,
2166 fn file_test_io_smoke_test() {
2167 let message = "it's alright. have a good time";
2168 let tmpdir = tmpdir();
2169 let filename = &tmpdir.join("file_rt_io_file_test.txt");
2171 let mut write_stream = check!(File::create(filename));
2172 check!(write_stream.write(message.as_bytes()));
2175 let mut read_stream = check!(File::open(filename));
2176 let mut read_buf = [0; 1028];
2177 let read_str = match check!(read_stream.read(&mut read_buf)) {
2178 0 => panic!("shouldn't happen"),
2179 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
2181 assert_eq!(read_str, message);
2183 check!(fs::remove_file(filename));
2187 fn invalid_path_raises() {
2188 let tmpdir = tmpdir();
2189 let filename = &tmpdir.join("file_that_does_not_exist.txt");
2190 let result = File::open(filename);
2193 error!(result, "No such file or directory");
2195 error!(result, 2); // ERROR_FILE_NOT_FOUND
2199 fn file_test_iounlinking_invalid_path_should_raise_condition() {
2200 let tmpdir = tmpdir();
2201 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
2203 let result = fs::remove_file(filename);
2206 error!(result, "No such file or directory");
2208 error!(result, 2); // ERROR_FILE_NOT_FOUND
2212 fn file_test_io_non_positional_read() {
2213 let message: &str = "ten-four";
2214 let mut read_mem = [0; 8];
2215 let tmpdir = tmpdir();
2216 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
2218 let mut rw_stream = check!(File::create(filename));
2219 check!(rw_stream.write(message.as_bytes()));
2222 let mut read_stream = check!(File::open(filename));
2224 let read_buf = &mut read_mem[0..4];
2225 check!(read_stream.read(read_buf));
2228 let read_buf = &mut read_mem[4..8];
2229 check!(read_stream.read(read_buf));
2232 check!(fs::remove_file(filename));
2233 let read_str = str::from_utf8(&read_mem).unwrap();
2234 assert_eq!(read_str, message);
2238 fn file_test_io_seek_and_tell_smoke_test() {
2239 let message = "ten-four";
2240 let mut read_mem = [0; 4];
2241 let set_cursor = 4 as u64;
2242 let tell_pos_pre_read;
2243 let tell_pos_post_read;
2244 let tmpdir = tmpdir();
2245 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
2247 let mut rw_stream = check!(File::create(filename));
2248 check!(rw_stream.write(message.as_bytes()));
2251 let mut read_stream = check!(File::open(filename));
2252 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
2253 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
2254 check!(read_stream.read(&mut read_mem));
2255 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
2257 check!(fs::remove_file(filename));
2258 let read_str = str::from_utf8(&read_mem).unwrap();
2259 assert_eq!(read_str, &message[4..8]);
2260 assert_eq!(tell_pos_pre_read, set_cursor);
2261 assert_eq!(tell_pos_post_read, message.len() as u64);
2265 fn file_test_io_seek_and_write() {
2266 let initial_msg = "food-is-yummy";
2267 let overwrite_msg = "-the-bar!!";
2268 let final_msg = "foo-the-bar!!";
2270 let mut read_mem = [0; 13];
2271 let tmpdir = tmpdir();
2272 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
2274 let mut rw_stream = check!(File::create(filename));
2275 check!(rw_stream.write(initial_msg.as_bytes()));
2276 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
2277 check!(rw_stream.write(overwrite_msg.as_bytes()));
2280 let mut read_stream = check!(File::open(filename));
2281 check!(read_stream.read(&mut read_mem));
2283 check!(fs::remove_file(filename));
2284 let read_str = str::from_utf8(&read_mem).unwrap();
2285 assert!(read_str == final_msg);
2289 fn file_test_io_seek_shakedown() {
2291 let initial_msg = "qwer-asdf-zxcv";
2292 let chunk_one: &str = "qwer";
2293 let chunk_two: &str = "asdf";
2294 let chunk_three: &str = "zxcv";
2295 let mut read_mem = [0; 4];
2296 let tmpdir = tmpdir();
2297 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2299 let mut rw_stream = check!(File::create(filename));
2300 check!(rw_stream.write(initial_msg.as_bytes()));
2303 let mut read_stream = check!(File::open(filename));
2305 check!(read_stream.seek(SeekFrom::End(-4)));
2306 check!(read_stream.read(&mut read_mem));
2307 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2309 check!(read_stream.seek(SeekFrom::Current(-9)));
2310 check!(read_stream.read(&mut read_mem));
2311 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2313 check!(read_stream.seek(SeekFrom::Start(0)));
2314 check!(read_stream.read(&mut read_mem));
2315 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2317 check!(fs::remove_file(filename));
2321 fn file_test_io_eof() {
2322 let tmpdir = tmpdir();
2323 let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2324 let mut buf = [0; 256];
2326 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2327 let mut rw = check!(oo.open(&filename));
2328 assert_eq!(check!(rw.read(&mut buf)), 0);
2329 assert_eq!(check!(rw.read(&mut buf)), 0);
2331 check!(fs::remove_file(&filename));
2336 fn file_test_io_read_write_at() {
2337 use os::unix::fs::FileExt;
2339 let tmpdir = tmpdir();
2340 let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2341 let mut buf = [0; 256];
2342 let write1 = "asdf";
2343 let write2 = "qwer-";
2344 let write3 = "-zxcv";
2345 let content = "qwer-asdf-zxcv";
2347 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2348 let mut rw = check!(oo.open(&filename));
2349 assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2350 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2351 assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2352 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2353 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2354 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2355 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2356 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2357 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2358 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2359 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2360 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2361 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2362 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2363 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2364 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2365 assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2366 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2369 let mut read = check!(File::open(&filename));
2370 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2371 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2372 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2373 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2374 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2375 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2376 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2377 assert_eq!(check!(read.read(&mut buf)), write3.len());
2378 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2379 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2380 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2381 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2382 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2383 assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2384 assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2385 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2387 check!(fs::remove_file(&filename));
2392 fn set_get_unix_permissions() {
2393 use os::unix::fs::PermissionsExt;
2395 let tmpdir = tmpdir();
2396 let filename = &tmpdir.join("set_get_unix_permissions");
2397 check!(fs::create_dir(filename));
2400 check!(fs::set_permissions(filename,
2401 fs::Permissions::from_mode(0)));
2402 let metadata0 = check!(fs::metadata(filename));
2403 assert_eq!(mask & metadata0.permissions().mode(), 0);
2405 check!(fs::set_permissions(filename,
2406 fs::Permissions::from_mode(0o1777)));
2407 let metadata1 = check!(fs::metadata(filename));
2408 assert_eq!(mask & metadata1.permissions().mode(), 0o1777);
2413 fn file_test_io_seek_read_write() {
2414 use os::windows::fs::FileExt;
2416 let tmpdir = tmpdir();
2417 let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2418 let mut buf = [0; 256];
2419 let write1 = "asdf";
2420 let write2 = "qwer-";
2421 let write3 = "-zxcv";
2422 let content = "qwer-asdf-zxcv";
2424 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2425 let mut rw = check!(oo.open(&filename));
2426 assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2427 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2428 assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2429 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2430 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2431 assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2432 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2433 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2434 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2435 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2436 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2437 assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2438 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2439 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2440 assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2441 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2444 let mut read = check!(File::open(&filename));
2445 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2446 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2447 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2448 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2449 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2450 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2451 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2452 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2453 assert_eq!(check!(read.read(&mut buf)), write3.len());
2454 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2455 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2456 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2457 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2458 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2459 assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2460 assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2462 check!(fs::remove_file(&filename));
2466 fn file_test_stat_is_correct_on_is_file() {
2467 let tmpdir = tmpdir();
2468 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2470 let mut opts = OpenOptions::new();
2471 let mut fs = check!(opts.read(true).write(true)
2472 .create(true).open(filename));
2474 fs.write(msg.as_bytes()).unwrap();
2476 let fstat_res = check!(fs.metadata());
2477 assert!(fstat_res.is_file());
2479 let stat_res_fn = check!(fs::metadata(filename));
2480 assert!(stat_res_fn.is_file());
2481 let stat_res_meth = check!(filename.metadata());
2482 assert!(stat_res_meth.is_file());
2483 check!(fs::remove_file(filename));
2487 fn file_test_stat_is_correct_on_is_dir() {
2488 let tmpdir = tmpdir();
2489 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2490 check!(fs::create_dir(filename));
2491 let stat_res_fn = check!(fs::metadata(filename));
2492 assert!(stat_res_fn.is_dir());
2493 let stat_res_meth = check!(filename.metadata());
2494 assert!(stat_res_meth.is_dir());
2495 check!(fs::remove_dir(filename));
2499 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2500 let tmpdir = tmpdir();
2501 let dir = &tmpdir.join("fileinfo_false_on_dir");
2502 check!(fs::create_dir(dir));
2503 assert!(!dir.is_file());
2504 check!(fs::remove_dir(dir));
2508 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2509 let tmpdir = tmpdir();
2510 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2511 check!(check!(File::create(file)).write(b"foo"));
2512 assert!(file.exists());
2513 check!(fs::remove_file(file));
2514 assert!(!file.exists());
2518 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2519 let tmpdir = tmpdir();
2520 let dir = &tmpdir.join("before_and_after_dir");
2521 assert!(!dir.exists());
2522 check!(fs::create_dir(dir));
2523 assert!(dir.exists());
2524 assert!(dir.is_dir());
2525 check!(fs::remove_dir(dir));
2526 assert!(!dir.exists());
2530 fn file_test_directoryinfo_readdir() {
2531 let tmpdir = tmpdir();
2532 let dir = &tmpdir.join("di_readdir");
2533 check!(fs::create_dir(dir));
2536 let f = dir.join(&format!("{}.txt", n));
2537 let mut w = check!(File::create(&f));
2538 let msg_str = format!("{}{}", prefix, n.to_string());
2539 let msg = msg_str.as_bytes();
2540 check!(w.write(msg));
2542 let files = check!(fs::read_dir(dir));
2543 let mut mem = [0; 4];
2545 let f = f.unwrap().path();
2547 let n = f.file_stem().unwrap();
2548 check!(check!(File::open(&f)).read(&mut mem));
2549 let read_str = str::from_utf8(&mem).unwrap();
2550 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2551 assert_eq!(expected, read_str);
2553 check!(fs::remove_file(&f));
2555 check!(fs::remove_dir(dir));
2559 fn file_create_new_already_exists_error() {
2560 let tmpdir = tmpdir();
2561 let file = &tmpdir.join("file_create_new_error_exists");
2562 check!(fs::File::create(file));
2563 let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2564 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2568 fn mkdir_path_already_exists_error() {
2569 let tmpdir = tmpdir();
2570 let dir = &tmpdir.join("mkdir_error_twice");
2571 check!(fs::create_dir(dir));
2572 let e = fs::create_dir(dir).unwrap_err();
2573 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2577 fn recursive_mkdir() {
2578 let tmpdir = tmpdir();
2579 let dir = tmpdir.join("d1/d2");
2580 check!(fs::create_dir_all(&dir));
2581 assert!(dir.is_dir())
2585 fn recursive_mkdir_failure() {
2586 let tmpdir = tmpdir();
2587 let dir = tmpdir.join("d1");
2588 let file = dir.join("f1");
2590 check!(fs::create_dir_all(&dir));
2591 check!(File::create(&file));
2593 let result = fs::create_dir_all(&file);
2595 assert!(result.is_err());
2599 fn concurrent_recursive_mkdir() {
2602 let mut dir = dir.join("a");
2604 dir = dir.join("a");
2606 let mut join = vec!();
2608 let dir = dir.clone();
2609 join.push(thread::spawn(move || {
2610 check!(fs::create_dir_all(&dir));
2614 // No `Display` on result of `join()`
2615 join.drain(..).map(|join| join.join().unwrap()).count();
2620 fn recursive_mkdir_slash() {
2621 check!(fs::create_dir_all(Path::new("/")));
2625 fn recursive_mkdir_dot() {
2626 check!(fs::create_dir_all(Path::new(".")));
2630 fn recursive_mkdir_empty() {
2631 check!(fs::create_dir_all(Path::new("")));
2635 fn recursive_rmdir() {
2636 let tmpdir = tmpdir();
2637 let d1 = tmpdir.join("d1");
2638 let dt = d1.join("t");
2639 let dtt = dt.join("t");
2640 let d2 = tmpdir.join("d2");
2641 let canary = d2.join("do_not_delete");
2642 check!(fs::create_dir_all(&dtt));
2643 check!(fs::create_dir_all(&d2));
2644 check!(check!(File::create(&canary)).write(b"foo"));
2645 check!(symlink_junction(&d2, &dt.join("d2")));
2646 let _ = symlink_file(&canary, &d1.join("canary"));
2647 check!(fs::remove_dir_all(&d1));
2649 assert!(!d1.is_dir());
2650 assert!(canary.exists());
2654 fn recursive_rmdir_of_symlink() {
2655 // test we do not recursively delete a symlink but only dirs.
2656 let tmpdir = tmpdir();
2657 let link = tmpdir.join("d1");
2658 let dir = tmpdir.join("d2");
2659 let canary = dir.join("do_not_delete");
2660 check!(fs::create_dir_all(&dir));
2661 check!(check!(File::create(&canary)).write(b"foo"));
2662 check!(symlink_junction(&dir, &link));
2663 check!(fs::remove_dir_all(&link));
2665 assert!(!link.is_dir());
2666 assert!(canary.exists());
2670 // only Windows makes a distinction between file and directory symlinks.
2672 fn recursive_rmdir_of_file_symlink() {
2673 let tmpdir = tmpdir();
2674 if !got_symlink_permission(&tmpdir) { return };
2676 let f1 = tmpdir.join("f1");
2677 let f2 = tmpdir.join("f2");
2678 check!(check!(File::create(&f1)).write(b"foo"));
2679 check!(symlink_file(&f1, &f2));
2680 match fs::remove_dir_all(&f2) {
2681 Ok(..) => panic!("wanted a failure"),
2687 fn unicode_path_is_dir() {
2688 assert!(Path::new(".").is_dir());
2689 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2691 let tmpdir = tmpdir();
2693 let mut dirpath = tmpdir.path().to_path_buf();
2694 dirpath.push("test-가一ー你好");
2695 check!(fs::create_dir(&dirpath));
2696 assert!(dirpath.is_dir());
2698 let mut filepath = dirpath;
2699 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2700 check!(File::create(&filepath)); // ignore return; touch only
2701 assert!(!filepath.is_dir());
2702 assert!(filepath.exists());
2706 fn unicode_path_exists() {
2707 assert!(Path::new(".").exists());
2708 assert!(!Path::new("test/nonexistent-bogus-path").exists());
2710 let tmpdir = tmpdir();
2711 let unicode = tmpdir.path();
2712 let unicode = unicode.join("test-각丁ー再见");
2713 check!(fs::create_dir(&unicode));
2714 assert!(unicode.exists());
2715 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2719 fn copy_file_does_not_exist() {
2720 let from = Path::new("test/nonexistent-bogus-path");
2721 let to = Path::new("test/other-bogus-path");
2723 match fs::copy(&from, &to) {
2726 assert!(!from.exists());
2727 assert!(!to.exists());
2733 fn copy_src_does_not_exist() {
2734 let tmpdir = tmpdir();
2735 let from = Path::new("test/nonexistent-bogus-path");
2736 let to = tmpdir.join("out.txt");
2737 check!(check!(File::create(&to)).write(b"hello"));
2738 assert!(fs::copy(&from, &to).is_err());
2739 assert!(!from.exists());
2740 let mut v = Vec::new();
2741 check!(check!(File::open(&to)).read_to_end(&mut v));
2742 assert_eq!(v, b"hello");
2747 let tmpdir = tmpdir();
2748 let input = tmpdir.join("in.txt");
2749 let out = tmpdir.join("out.txt");
2751 check!(check!(File::create(&input)).write(b"hello"));
2752 check!(fs::copy(&input, &out));
2753 let mut v = Vec::new();
2754 check!(check!(File::open(&out)).read_to_end(&mut v));
2755 assert_eq!(v, b"hello");
2757 assert_eq!(check!(input.metadata()).permissions(),
2758 check!(out.metadata()).permissions());
2762 fn copy_file_dst_dir() {
2763 let tmpdir = tmpdir();
2764 let out = tmpdir.join("out");
2766 check!(File::create(&out));
2767 match fs::copy(&*out, tmpdir.path()) {
2768 Ok(..) => panic!(), Err(..) => {}
2773 fn copy_file_dst_exists() {
2774 let tmpdir = tmpdir();
2775 let input = tmpdir.join("in");
2776 let output = tmpdir.join("out");
2778 check!(check!(File::create(&input)).write("foo".as_bytes()));
2779 check!(check!(File::create(&output)).write("bar".as_bytes()));
2780 check!(fs::copy(&input, &output));
2782 let mut v = Vec::new();
2783 check!(check!(File::open(&output)).read_to_end(&mut v));
2784 assert_eq!(v, b"foo".to_vec());
2788 fn copy_file_src_dir() {
2789 let tmpdir = tmpdir();
2790 let out = tmpdir.join("out");
2792 match fs::copy(tmpdir.path(), &out) {
2793 Ok(..) => panic!(), Err(..) => {}
2795 assert!(!out.exists());
2799 fn copy_file_preserves_perm_bits() {
2800 let tmpdir = tmpdir();
2801 let input = tmpdir.join("in.txt");
2802 let out = tmpdir.join("out.txt");
2804 let attr = check!(check!(File::create(&input)).metadata());
2805 let mut p = attr.permissions();
2806 p.set_readonly(true);
2807 check!(fs::set_permissions(&input, p));
2808 check!(fs::copy(&input, &out));
2809 assert!(check!(out.metadata()).permissions().readonly());
2810 check!(fs::set_permissions(&input, attr.permissions()));
2811 check!(fs::set_permissions(&out, attr.permissions()));
2816 fn copy_file_preserves_streams() {
2818 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2819 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 0);
2820 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2821 let mut v = Vec::new();
2822 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2823 assert_eq!(v, b"carrot".to_vec());
2827 fn copy_file_returns_metadata_len() {
2829 let in_path = tmp.join("in.txt");
2830 let out_path = tmp.join("out.txt");
2831 check!(check!(File::create(&in_path)).write(b"lettuce"));
2833 check!(check!(File::create(tmp.join("in.txt:bunny"))).write(b"carrot"));
2834 let copied_len = check!(fs::copy(&in_path, &out_path));
2835 assert_eq!(check!(out_path.metadata()).len(), copied_len);
2839 fn symlinks_work() {
2840 let tmpdir = tmpdir();
2841 if !got_symlink_permission(&tmpdir) { return };
2843 let input = tmpdir.join("in.txt");
2844 let out = tmpdir.join("out.txt");
2846 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2847 check!(symlink_file(&input, &out));
2848 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
2849 assert_eq!(check!(fs::metadata(&out)).len(),
2850 check!(fs::metadata(&input)).len());
2851 let mut v = Vec::new();
2852 check!(check!(File::open(&out)).read_to_end(&mut v));
2853 assert_eq!(v, b"foobar".to_vec());
2857 fn symlink_noexist() {
2858 // Symlinks can point to things that don't exist
2859 let tmpdir = tmpdir();
2860 if !got_symlink_permission(&tmpdir) { return };
2862 // Use a relative path for testing. Symlinks get normalized by Windows,
2863 // so we may not get the same path back for absolute paths
2864 check!(symlink_file(&"foo", &tmpdir.join("bar")));
2865 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(),
2872 // directory symlink
2873 assert_eq!(check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
2876 assert_eq!(check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
2877 r"C:\Users\Default");
2878 // junction with special permissions
2879 assert_eq!(check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
2882 let tmpdir = tmpdir();
2883 let link = tmpdir.join("link");
2884 if !got_symlink_permission(&tmpdir) { return };
2885 check!(symlink_file(&"foo", &link));
2886 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
2890 fn readlink_not_symlink() {
2891 let tmpdir = tmpdir();
2892 match fs::read_link(tmpdir.path()) {
2893 Ok(..) => panic!("wanted a failure"),
2900 let tmpdir = tmpdir();
2901 let input = tmpdir.join("in.txt");
2902 let out = tmpdir.join("out.txt");
2904 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2905 check!(fs::hard_link(&input, &out));
2906 assert_eq!(check!(fs::metadata(&out)).len(),
2907 check!(fs::metadata(&input)).len());
2908 assert_eq!(check!(fs::metadata(&out)).len(),
2909 check!(input.metadata()).len());
2910 let mut v = Vec::new();
2911 check!(check!(File::open(&out)).read_to_end(&mut v));
2912 assert_eq!(v, b"foobar".to_vec());
2914 // can't link to yourself
2915 match fs::hard_link(&input, &input) {
2916 Ok(..) => panic!("wanted a failure"),
2919 // can't link to something that doesn't exist
2920 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
2921 Ok(..) => panic!("wanted a failure"),
2928 let tmpdir = tmpdir();
2929 let file = tmpdir.join("in.txt");
2931 check!(File::create(&file));
2932 let attr = check!(fs::metadata(&file));
2933 assert!(!attr.permissions().readonly());
2934 let mut p = attr.permissions();
2935 p.set_readonly(true);
2936 check!(fs::set_permissions(&file, p.clone()));
2937 let attr = check!(fs::metadata(&file));
2938 assert!(attr.permissions().readonly());
2940 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
2941 Ok(..) => panic!("wanted an error"),
2945 p.set_readonly(false);
2946 check!(fs::set_permissions(&file, p));
2951 let tmpdir = tmpdir();
2952 let path = tmpdir.join("in.txt");
2954 let file = check!(File::create(&path));
2955 let attr = check!(fs::metadata(&path));
2956 assert!(!attr.permissions().readonly());
2957 let mut p = attr.permissions();
2958 p.set_readonly(true);
2959 check!(file.set_permissions(p.clone()));
2960 let attr = check!(fs::metadata(&path));
2961 assert!(attr.permissions().readonly());
2963 p.set_readonly(false);
2964 check!(file.set_permissions(p));
2968 fn sync_doesnt_kill_anything() {
2969 let tmpdir = tmpdir();
2970 let path = tmpdir.join("in.txt");
2972 let mut file = check!(File::create(&path));
2973 check!(file.sync_all());
2974 check!(file.sync_data());
2975 check!(file.write(b"foo"));
2976 check!(file.sync_all());
2977 check!(file.sync_data());
2981 fn truncate_works() {
2982 let tmpdir = tmpdir();
2983 let path = tmpdir.join("in.txt");
2985 let mut file = check!(File::create(&path));
2986 check!(file.write(b"foo"));
2987 check!(file.sync_all());
2989 // Do some simple things with truncation
2990 assert_eq!(check!(file.metadata()).len(), 3);
2991 check!(file.set_len(10));
2992 assert_eq!(check!(file.metadata()).len(), 10);
2993 check!(file.write(b"bar"));
2994 check!(file.sync_all());
2995 assert_eq!(check!(file.metadata()).len(), 10);
2997 let mut v = Vec::new();
2998 check!(check!(File::open(&path)).read_to_end(&mut v));
2999 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
3001 // Truncate to a smaller length, don't seek, and then write something.
3002 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
3003 // past the end of the file).
3004 check!(file.set_len(2));
3005 assert_eq!(check!(file.metadata()).len(), 2);
3006 check!(file.write(b"wut"));
3007 check!(file.sync_all());
3008 assert_eq!(check!(file.metadata()).len(), 9);
3009 let mut v = Vec::new();
3010 check!(check!(File::open(&path)).read_to_end(&mut v));
3011 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
3016 use fs::OpenOptions as OO;
3017 fn c<T: Clone>(t: &T) -> T { t.clone() }
3019 let tmpdir = tmpdir();
3021 let mut r = OO::new(); r.read(true);
3022 let mut w = OO::new(); w.write(true);
3023 let mut rw = OO::new(); rw.read(true).write(true);
3024 let mut a = OO::new(); a.append(true);
3025 let mut ra = OO::new(); ra.read(true).append(true);
3028 let invalid_options = 87; // ERROR_INVALID_PARAMETER
3030 let invalid_options = "Invalid argument";
3032 // Test various combinations of creation modes and access modes.
3035 // creation mode | read | write | read-write | append | read-append |
3036 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
3037 // not set (open existing) | X | X | X | X | X |
3038 // create | | X | X | X | X |
3039 // truncate | | X | X | | |
3040 // create and truncate | | X | X | | |
3041 // create_new | | X | X | X | X |
3043 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
3046 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
3047 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
3048 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
3049 check!(c(&w).create(true).open(&tmpdir.join("a")));
3050 check!(c(&w).open(&tmpdir.join("a")));
3053 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
3054 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
3055 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
3056 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
3057 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
3060 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
3061 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
3062 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
3063 check!(c(&rw).create(true).open(&tmpdir.join("c")));
3064 check!(c(&rw).open(&tmpdir.join("c")));
3067 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
3068 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
3069 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
3070 check!(c(&a).create(true).open(&tmpdir.join("d")));
3071 check!(c(&a).open(&tmpdir.join("d")));
3074 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
3075 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
3076 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
3077 check!(c(&ra).create(true).open(&tmpdir.join("e")));
3078 check!(c(&ra).open(&tmpdir.join("e")));
3080 // Test opening a file without setting an access mode
3081 let mut blank = OO::new();
3082 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
3085 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
3087 // Test write fails for read-only
3088 check!(r.open(&tmpdir.join("h")));
3090 let mut f = check!(r.open(&tmpdir.join("h")));
3091 assert!(f.write("wut".as_bytes()).is_err());
3094 // Test write overwrites
3096 let mut f = check!(c(&w).open(&tmpdir.join("h")));
3097 check!(f.write("baz".as_bytes()));
3100 let mut f = check!(c(&r).open(&tmpdir.join("h")));
3101 let mut b = vec![0; 6];
3102 check!(f.read(&mut b));
3103 assert_eq!(b, "bazbar".as_bytes());
3106 // Test truncate works
3108 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
3109 check!(f.write("foo".as_bytes()));
3111 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3113 // Test append works
3114 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3116 let mut f = check!(c(&a).open(&tmpdir.join("h")));
3117 check!(f.write("bar".as_bytes()));
3119 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
3121 // Test .append(true) equals .write(true).append(true)
3123 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
3124 check!(f.write("baz".as_bytes()));
3126 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
3130 fn _assert_send_sync() {
3131 fn _assert_send_sync<T: Send + Sync>() {}
3132 _assert_send_sync::<OpenOptions>();
3137 let mut bytes = [0; 1024];
3138 StdRng::from_entropy().fill_bytes(&mut bytes);
3140 let tmpdir = tmpdir();
3142 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
3143 let mut v = Vec::new();
3144 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
3145 assert!(v == &bytes[..]);
3149 fn write_then_read() {
3150 let mut bytes = [0; 1024];
3151 StdRng::from_entropy().fill_bytes(&mut bytes);
3153 let tmpdir = tmpdir();
3155 check!(fs::write(&tmpdir.join("test"), &bytes[..]));
3156 let v = check!(fs::read(&tmpdir.join("test")));
3157 assert!(v == &bytes[..]);
3159 check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF]));
3160 error_contains!(fs::read_to_string(&tmpdir.join("not-utf8")),
3161 "stream did not contain valid UTF-8");
3164 check!(fs::write(&tmpdir.join("utf8"), s.as_bytes()));
3165 let string = check!(fs::read_to_string(&tmpdir.join("utf8")));
3166 assert_eq!(string, s);
3170 fn file_try_clone() {
3171 let tmpdir = tmpdir();
3173 let mut f1 = check!(OpenOptions::new()
3177 .open(&tmpdir.join("test")));
3178 let mut f2 = check!(f1.try_clone());
3180 check!(f1.write_all(b"hello world"));
3181 check!(f1.seek(SeekFrom::Start(2)));
3183 let mut buf = vec![];
3184 check!(f2.read_to_end(&mut buf));
3185 assert_eq!(buf, b"llo world");
3188 check!(f1.write_all(b"!"));
3192 #[cfg(not(windows))]
3193 fn unlink_readonly() {
3194 let tmpdir = tmpdir();
3195 let path = tmpdir.join("file");
3196 check!(File::create(&path));
3197 let mut perm = check!(fs::metadata(&path)).permissions();
3198 perm.set_readonly(true);
3199 check!(fs::set_permissions(&path, perm));
3200 check!(fs::remove_file(&path));
3204 fn mkdir_trailing_slash() {
3205 let tmpdir = tmpdir();
3206 let path = tmpdir.join("file");
3207 check!(fs::create_dir_all(&path.join("a/")));
3211 fn canonicalize_works_simple() {
3212 let tmpdir = tmpdir();
3213 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3214 let file = tmpdir.join("test");
3215 File::create(&file).unwrap();
3216 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3220 fn realpath_works() {
3221 let tmpdir = tmpdir();
3222 if !got_symlink_permission(&tmpdir) { return };
3224 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3225 let file = tmpdir.join("test");
3226 let dir = tmpdir.join("test2");
3227 let link = dir.join("link");
3228 let linkdir = tmpdir.join("test3");
3230 File::create(&file).unwrap();
3231 fs::create_dir(&dir).unwrap();
3232 symlink_file(&file, &link).unwrap();
3233 symlink_dir(&dir, &linkdir).unwrap();
3235 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
3237 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
3238 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3239 assert_eq!(fs::canonicalize(&link).unwrap(), file);
3240 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
3241 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
3245 fn realpath_works_tricky() {
3246 let tmpdir = tmpdir();
3247 if !got_symlink_permission(&tmpdir) { return };
3249 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3250 let a = tmpdir.join("a");
3251 let b = a.join("b");
3252 let c = b.join("c");
3253 let d = a.join("d");
3254 let e = d.join("e");
3255 let f = a.join("f");
3257 fs::create_dir_all(&b).unwrap();
3258 fs::create_dir_all(&d).unwrap();
3259 File::create(&f).unwrap();
3260 if cfg!(not(windows)) {
3261 symlink_dir("../d/e", &c).unwrap();
3262 symlink_file("../f", &e).unwrap();
3265 symlink_dir(r"..\d\e", &c).unwrap();
3266 symlink_file(r"..\f", &e).unwrap();
3269 assert_eq!(fs::canonicalize(&c).unwrap(), f);
3270 assert_eq!(fs::canonicalize(&e).unwrap(), f);
3274 fn dir_entry_methods() {
3275 let tmpdir = tmpdir();
3277 fs::create_dir_all(&tmpdir.join("a")).unwrap();
3278 File::create(&tmpdir.join("b")).unwrap();
3280 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
3281 let fname = file.file_name();
3282 match fname.to_str() {
3284 assert!(file.file_type().unwrap().is_dir());
3285 assert!(file.metadata().unwrap().is_dir());
3288 assert!(file.file_type().unwrap().is_file());
3289 assert!(file.metadata().unwrap().is_file());
3291 f => panic!("unknown file name: {:?}", f),
3297 fn dir_entry_debug() {
3298 let tmpdir = tmpdir();
3299 File::create(&tmpdir.join("b")).unwrap();
3300 let mut read_dir = tmpdir.path().read_dir().unwrap();
3301 let dir_entry = read_dir.next().unwrap().unwrap();
3302 let actual = format!("{:?}", dir_entry);
3303 let expected = format!("DirEntry({:?})", dir_entry.0.path());
3304 assert_eq!(actual, expected);
3308 fn read_dir_not_found() {
3309 let res = fs::read_dir("/path/that/does/not/exist");
3310 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
3314 fn create_dir_all_with_junctions() {
3315 let tmpdir = tmpdir();
3316 let target = tmpdir.join("target");
3318 let junction = tmpdir.join("junction");
3319 let b = junction.join("a/b");
3321 let link = tmpdir.join("link");
3322 let d = link.join("c/d");
3324 fs::create_dir(&target).unwrap();
3326 check!(symlink_junction(&target, &junction));
3327 check!(fs::create_dir_all(&b));
3328 // the junction itself is not a directory, but `is_dir()` on a Path
3330 assert!(junction.is_dir());
3331 assert!(b.exists());
3333 if !got_symlink_permission(&tmpdir) { return };
3334 check!(symlink_dir(&target, &link));
3335 check!(fs::create_dir_all(&d));
3336 assert!(link.is_dir());
3337 assert!(d.exists());
3341 fn metadata_access_times() {
3342 let tmpdir = tmpdir();
3344 let b = tmpdir.join("b");
3345 File::create(&b).unwrap();
3347 let a = check!(fs::metadata(&tmpdir.path()));
3348 let b = check!(fs::metadata(&b));
3350 assert_eq!(check!(a.accessed()), check!(a.accessed()));
3351 assert_eq!(check!(a.modified()), check!(a.modified()));
3352 assert_eq!(check!(b.accessed()), check!(b.modified()));
3354 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3355 check!(a.created());
3356 check!(b.created());