1 // ignore-tidy-filelength
3 //! Filesystem manipulation operations.
5 //! This module contains basic methods to manipulate the contents of the local
6 //! filesystem. All methods in this module represent cross-platform filesystem
7 //! operations. Extra platform-specific functionality can be found in the
8 //! extension traits of `std::os::$platform`.
10 #![stable(feature = "rust1", since = "1.0.0")]
13 use crate::ffi::OsString;
14 use crate::io::{self, SeekFrom, Seek, Read, Initializer, Write, IoSlice, IoSliceMut};
15 use crate::path::{Path, PathBuf};
16 use crate::sys::fs as fs_imp;
17 use crate::sys_common::{AsInnerMut, FromInner, AsInner, IntoInner};
18 use crate::time::SystemTime;
20 /// A reference to an open file on the filesystem.
22 /// An instance of a `File` can be read and/or written depending on what options
23 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
24 /// that the file contains internally.
26 /// Files are automatically closed when they go out of scope. Errors detected
27 /// on closing are ignored by the implementation of `Drop`. Use the method
28 /// [`sync_all`] if these errors must be manually handled.
32 /// Creates a new file and write bytes to it:
35 /// use std::fs::File;
36 /// use std::io::prelude::*;
38 /// fn main() -> std::io::Result<()> {
39 /// let mut file = File::create("foo.txt")?;
40 /// file.write_all(b"Hello, world!")?;
45 /// Read the contents of a file into a [`String`]:
48 /// use std::fs::File;
49 /// use std::io::prelude::*;
51 /// fn main() -> std::io::Result<()> {
52 /// let mut file = File::open("foo.txt")?;
53 /// let mut contents = String::new();
54 /// file.read_to_string(&mut contents)?;
55 /// assert_eq!(contents, "Hello, world!");
60 /// It can be more efficient to read the contents of a file with a buffered
61 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
64 /// use std::fs::File;
65 /// use std::io::BufReader;
66 /// use std::io::prelude::*;
68 /// fn main() -> std::io::Result<()> {
69 /// let file = File::open("foo.txt")?;
70 /// let mut buf_reader = BufReader::new(file);
71 /// let mut contents = String::new();
72 /// buf_reader.read_to_string(&mut contents)?;
73 /// assert_eq!(contents, "Hello, world!");
78 /// Note that, although read and write methods require a `&mut File`, because
79 /// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
80 /// still modify the file, either through methods that take `&File` or by
81 /// retrieving the underlying OS object and modifying the file that way.
82 /// Additionally, many operating systems allow concurrent modification of files
83 /// by different processes. Avoid assuming that holding a `&File` means that the
84 /// file will not change.
86 /// [`Seek`]: ../io/trait.Seek.html
87 /// [`String`]: ../string/struct.String.html
88 /// [`Read`]: ../io/trait.Read.html
89 /// [`Write`]: ../io/trait.Write.html
90 /// [`BufReader<R>`]: ../io/struct.BufReader.html
91 /// [`sync_all`]: struct.File.html#method.sync_all
92 #[stable(feature = "rust1", since = "1.0.0")]
97 /// Metadata information about a file.
99 /// This structure is returned from the [`metadata`] or
100 /// [`symlink_metadata`] function or method and represents known
101 /// metadata about a file such as its permissions, size, modification
104 /// [`metadata`]: fn.metadata.html
105 /// [`symlink_metadata`]: fn.symlink_metadata.html
106 #[stable(feature = "rust1", since = "1.0.0")]
108 pub struct Metadata(fs_imp::FileAttr);
110 /// Iterator over the entries in a directory.
112 /// This iterator is returned from the [`read_dir`] function of this module and
113 /// will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. Through a [`DirEntry`]
114 /// information like the entry's path and possibly other metadata can be
119 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
120 /// IO error during iteration.
122 /// [`read_dir`]: fn.read_dir.html
123 /// [`DirEntry`]: struct.DirEntry.html
124 /// [`io::Result`]: ../io/type.Result.html
125 /// [`Err`]: ../result/enum.Result.html#variant.Err
126 #[stable(feature = "rust1", since = "1.0.0")]
128 pub struct ReadDir(fs_imp::ReadDir);
130 /// Entries returned by the [`ReadDir`] iterator.
132 /// [`ReadDir`]: struct.ReadDir.html
134 /// An instance of `DirEntry` represents an entry inside of a directory on the
135 /// filesystem. Each entry can be inspected via methods to learn about the full
136 /// path or possibly other metadata through per-platform extension traits.
137 #[stable(feature = "rust1", since = "1.0.0")]
138 pub struct DirEntry(fs_imp::DirEntry);
140 /// Options and flags which can be used to configure how a file is opened.
142 /// This builder exposes the ability to configure how a [`File`] is opened and
143 /// what operations are permitted on the open file. The [`File::open`] and
144 /// [`File::create`] methods are aliases for commonly used options using this
147 /// [`File`]: struct.File.html
148 /// [`File::open`]: struct.File.html#method.open
149 /// [`File::create`]: struct.File.html#method.create
151 /// Generally speaking, when using `OpenOptions`, you'll first call [`new`],
152 /// then chain calls to methods to set each option, then call [`open`],
153 /// passing the path of the file you're trying to open. This will give you a
154 /// [`io::Result`][result] with a [`File`][file] inside that you can further
157 /// [`new`]: struct.OpenOptions.html#method.new
158 /// [`open`]: struct.OpenOptions.html#method.open
159 /// [result]: ../io/type.Result.html
160 /// [file]: struct.File.html
164 /// Opening a file to read:
167 /// use std::fs::OpenOptions;
169 /// let file = OpenOptions::new().read(true).open("foo.txt");
172 /// Opening a file for both reading and writing, as well as creating it if it
176 /// use std::fs::OpenOptions;
178 /// let file = OpenOptions::new()
182 /// .open("foo.txt");
184 #[derive(Clone, Debug)]
185 #[stable(feature = "rust1", since = "1.0.0")]
186 pub struct OpenOptions(fs_imp::OpenOptions);
188 /// Representation of the various permissions on a file.
190 /// This module only currently provides one bit of information, [`readonly`],
191 /// which is exposed on all currently supported platforms. Unix-specific
192 /// functionality, such as mode bits, is available through the
193 /// [`PermissionsExt`] trait.
195 /// [`readonly`]: struct.Permissions.html#method.readonly
196 /// [`PermissionsExt`]: ../os/unix/fs/trait.PermissionsExt.html
197 #[derive(Clone, PartialEq, Eq, Debug)]
198 #[stable(feature = "rust1", since = "1.0.0")]
199 pub struct Permissions(fs_imp::FilePermissions);
201 /// A structure representing a type of file with accessors for each file type.
202 /// It is returned by [`Metadata::file_type`] method.
204 /// [`Metadata::file_type`]: struct.Metadata.html#method.file_type
205 #[stable(feature = "file_type", since = "1.1.0")]
206 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
207 pub struct FileType(fs_imp::FileType);
209 /// A builder used to create directories in various manners.
211 /// This builder also supports platform-specific options.
212 #[stable(feature = "dir_builder", since = "1.6.0")]
214 pub struct DirBuilder {
215 inner: fs_imp::DirBuilder,
219 /// Indicates how large a buffer to pre-allocate before reading the entire file.
220 fn initial_buffer_size(file: &File) -> usize {
221 // Allocate one extra byte so the buffer doesn't need to grow before the
222 // final `read` call at the end of the file. Don't worry about `usize`
223 // overflow because reading will fail regardless in that case.
224 file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
227 /// Read the entire contents of a file into a bytes vector.
229 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
230 /// with fewer imports and without an intermediate variable. It pre-allocates a
231 /// buffer based on the file size when available, so it is generally faster than
232 /// reading into a vector created with `Vec::new()`.
234 /// [`File::open`]: struct.File.html#method.open
235 /// [`read_to_end`]: ../io/trait.Read.html#method.read_to_end
239 /// This function will return an error if `path` does not already exist.
240 /// Other errors may also be returned according to [`OpenOptions::open`].
242 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
244 /// It will also return an error if it encounters while reading an error
245 /// of a kind other than [`ErrorKind::Interrupted`].
247 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
253 /// use std::net::SocketAddr;
255 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
256 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
260 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
261 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
262 fn inner(path: &Path) -> io::Result<Vec<u8>> {
263 let mut file = File::open(path)?;
264 let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
265 file.read_to_end(&mut bytes)?;
271 /// Read the entire contents of a file into a string.
273 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
274 /// with fewer imports and without an intermediate variable. It pre-allocates a
275 /// buffer based on the file size when available, so it is generally faster than
276 /// reading into a string created with `String::new()`.
278 /// [`File::open`]: struct.File.html#method.open
279 /// [`read_to_string`]: ../io/trait.Read.html#method.read_to_string
283 /// This function will return an error if `path` does not already exist.
284 /// Other errors may also be returned according to [`OpenOptions::open`].
286 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
288 /// It will also return an error if it encounters while reading an error
289 /// of a kind other than [`ErrorKind::Interrupted`],
290 /// or if the contents of the file are not valid UTF-8.
292 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
298 /// use std::net::SocketAddr;
300 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
301 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
305 #[stable(feature = "fs_read_write", since = "1.26.0")]
306 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
307 fn inner(path: &Path) -> io::Result<String> {
308 let mut file = File::open(path)?;
309 let mut string = String::with_capacity(initial_buffer_size(&file));
310 file.read_to_string(&mut string)?;
316 /// Write a slice as the entire contents of a file.
318 /// This function will create a file if it does not exist,
319 /// and will entirely replace its contents if it does.
321 /// This is a convenience function for using [`File::create`] and [`write_all`]
322 /// with fewer imports.
324 /// [`File::create`]: struct.File.html#method.create
325 /// [`write_all`]: ../io/trait.Write.html#method.write_all
332 /// fn main() -> std::io::Result<()> {
333 /// fs::write("foo.txt", b"Lorem ipsum")?;
334 /// fs::write("bar.txt", "dolor sit")?;
338 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
339 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
340 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
341 File::create(path)?.write_all(contents)
343 inner(path.as_ref(), contents.as_ref())
347 /// Attempts to open a file in read-only mode.
349 /// See the [`OpenOptions::open`] method for more details.
353 /// This function will return an error if `path` does not already exist.
354 /// Other errors may also be returned according to [`OpenOptions::open`].
356 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
361 /// use std::fs::File;
363 /// fn main() -> std::io::Result<()> {
364 /// let mut f = File::open("foo.txt")?;
368 #[stable(feature = "rust1", since = "1.0.0")]
369 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
370 OpenOptions::new().read(true).open(path.as_ref())
373 /// Opens a file in write-only mode.
375 /// This function will create a file if it does not exist,
376 /// and will truncate it if it does.
378 /// See the [`OpenOptions::open`] function for more details.
380 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
385 /// use std::fs::File;
387 /// fn main() -> std::io::Result<()> {
388 /// let mut f = File::create("foo.txt")?;
392 #[stable(feature = "rust1", since = "1.0.0")]
393 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
394 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
397 /// Attempts to sync all OS-internal metadata to disk.
399 /// This function will attempt to ensure that all in-memory data reaches the
400 /// filesystem before returning.
402 /// This can be used to handle errors that would otherwise only be caught
403 /// when the `File` is closed. Dropping a file will ignore errors in
404 /// synchronizing this in-memory data.
409 /// use std::fs::File;
410 /// use std::io::prelude::*;
412 /// fn main() -> std::io::Result<()> {
413 /// let mut f = File::create("foo.txt")?;
414 /// f.write_all(b"Hello, world!")?;
420 #[stable(feature = "rust1", since = "1.0.0")]
421 pub fn sync_all(&self) -> io::Result<()> {
425 /// This function is similar to [`sync_all`], except that it may not
426 /// synchronize file metadata to the filesystem.
428 /// This is intended for use cases that must synchronize content, but don't
429 /// need the metadata on disk. The goal of this method is to reduce disk
432 /// Note that some platforms may simply implement this in terms of
435 /// [`sync_all`]: struct.File.html#method.sync_all
440 /// use std::fs::File;
441 /// use std::io::prelude::*;
443 /// fn main() -> std::io::Result<()> {
444 /// let mut f = File::create("foo.txt")?;
445 /// f.write_all(b"Hello, world!")?;
451 #[stable(feature = "rust1", since = "1.0.0")]
452 pub fn sync_data(&self) -> io::Result<()> {
453 self.inner.datasync()
456 /// Truncates or extends the underlying file, updating the size of
457 /// this file to become `size`.
459 /// If the `size` is less than the current file's size, then the file will
460 /// be shrunk. If it is greater than the current file's size, then the file
461 /// will be extended to `size` and have all of the intermediate data filled
464 /// The file's cursor isn't changed. In particular, if the cursor was at the
465 /// end and the file is shrunk using this operation, the cursor will now be
470 /// This function will return an error if the file is not opened for writing.
475 /// use std::fs::File;
477 /// fn main() -> std::io::Result<()> {
478 /// let mut f = File::create("foo.txt")?;
484 /// Note that this method alters the content of the underlying file, even
485 /// though it takes `&self` rather than `&mut self`.
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub fn set_len(&self, size: u64) -> io::Result<()> {
488 self.inner.truncate(size)
491 /// Queries metadata about the underlying file.
496 /// use std::fs::File;
498 /// fn main() -> std::io::Result<()> {
499 /// let mut f = File::open("foo.txt")?;
500 /// let metadata = f.metadata()?;
504 #[stable(feature = "rust1", since = "1.0.0")]
505 pub fn metadata(&self) -> io::Result<Metadata> {
506 self.inner.file_attr().map(Metadata)
509 /// Creates a new `File` instance that shares the same underlying file handle
510 /// as the existing `File` instance. Reads, writes, and seeks will affect
511 /// both `File` instances simultaneously.
515 /// Creates two handles for a file named `foo.txt`:
518 /// use std::fs::File;
520 /// fn main() -> std::io::Result<()> {
521 /// let mut file = File::open("foo.txt")?;
522 /// let file_copy = file.try_clone()?;
527 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
528 /// two handles, seek one of them, and read the remaining bytes from the
532 /// use std::fs::File;
533 /// use std::io::SeekFrom;
534 /// use std::io::prelude::*;
536 /// fn main() -> std::io::Result<()> {
537 /// let mut file = File::open("foo.txt")?;
538 /// let mut file_copy = file.try_clone()?;
540 /// file.seek(SeekFrom::Start(3))?;
542 /// let mut contents = vec![];
543 /// file_copy.read_to_end(&mut contents)?;
544 /// assert_eq!(contents, b"def\n");
548 #[stable(feature = "file_try_clone", since = "1.9.0")]
549 pub fn try_clone(&self) -> io::Result<File> {
551 inner: self.inner.duplicate()?
555 /// Changes the permissions on the underlying file.
557 /// # Platform-specific behavior
559 /// This function currently corresponds to the `fchmod` function on Unix and
560 /// the `SetFileInformationByHandle` function on Windows. Note that, this
561 /// [may change in the future][changes].
563 /// [changes]: ../io/index.html#platform-specific-behavior
567 /// This function will return an error if the user lacks permission change
568 /// attributes on the underlying file. It may also return an error in other
569 /// os-specific unspecified cases.
574 /// fn main() -> std::io::Result<()> {
575 /// use std::fs::File;
577 /// let file = File::open("foo.txt")?;
578 /// let mut perms = file.metadata()?.permissions();
579 /// perms.set_readonly(true);
580 /// file.set_permissions(perms)?;
585 /// Note that this method alters the permissions of the underlying file,
586 /// even though it takes `&self` rather than `&mut self`.
587 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
588 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
589 self.inner.set_permissions(perm.0)
593 impl AsInner<fs_imp::File> for File {
594 fn as_inner(&self) -> &fs_imp::File { &self.inner }
596 impl FromInner<fs_imp::File> for File {
597 fn from_inner(f: fs_imp::File) -> File {
601 impl IntoInner<fs_imp::File> for File {
602 fn into_inner(self) -> fs_imp::File {
607 #[stable(feature = "rust1", since = "1.0.0")]
608 impl fmt::Debug for File {
609 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614 #[stable(feature = "rust1", since = "1.0.0")]
616 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
620 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
621 self.inner.read_vectored(bufs)
625 unsafe fn initializer(&self) -> Initializer {
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl Write for File {
631 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
632 self.inner.write(buf)
635 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
636 self.inner.write_vectored(bufs)
639 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
641 #[stable(feature = "rust1", since = "1.0.0")]
643 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
647 #[stable(feature = "rust1", since = "1.0.0")]
648 impl Read for &File {
649 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
653 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
654 self.inner.read_vectored(bufs)
658 unsafe fn initializer(&self) -> Initializer {
662 #[stable(feature = "rust1", since = "1.0.0")]
663 impl Write for &File {
664 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
665 self.inner.write(buf)
668 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
669 self.inner.write_vectored(bufs)
672 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
674 #[stable(feature = "rust1", since = "1.0.0")]
675 impl Seek for &File {
676 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
682 /// Creates a blank new set of options ready for configuration.
684 /// All options are initially set to `false`.
689 /// use std::fs::OpenOptions;
691 /// let mut options = OpenOptions::new();
692 /// let file = options.read(true).open("foo.txt");
694 #[stable(feature = "rust1", since = "1.0.0")]
695 pub fn new() -> OpenOptions {
696 OpenOptions(fs_imp::OpenOptions::new())
699 /// Sets the option for read access.
701 /// This option, when true, will indicate that the file should be
702 /// `read`-able if opened.
707 /// use std::fs::OpenOptions;
709 /// let file = OpenOptions::new().read(true).open("foo.txt");
711 #[stable(feature = "rust1", since = "1.0.0")]
712 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
713 self.0.read(read); self
716 /// Sets the option for write access.
718 /// This option, when true, will indicate that the file should be
719 /// `write`-able if opened.
721 /// If the file already exists, any write calls on it will overwrite its
722 /// contents, without truncating it.
727 /// use std::fs::OpenOptions;
729 /// let file = OpenOptions::new().write(true).open("foo.txt");
731 #[stable(feature = "rust1", since = "1.0.0")]
732 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
733 self.0.write(write); self
736 /// Sets the option for the append mode.
738 /// This option, when true, means that writes will append to a file instead
739 /// of overwriting previous contents.
740 /// Note that setting `.write(true).append(true)` has the same effect as
741 /// setting only `.append(true)`.
743 /// For most filesystems, the operating system guarantees that all writes are
744 /// atomic: no writes get mangled because another process writes at the same
747 /// One maybe obvious note when using append-mode: make sure that all data
748 /// that belongs together is written to the file in one operation. This
749 /// can be done by concatenating strings before passing them to [`write()`],
750 /// or using a buffered writer (with a buffer of adequate size),
751 /// and calling [`flush()`] when the message is complete.
753 /// If a file is opened with both read and append access, beware that after
754 /// opening, and after every write, the position for reading may be set at the
755 /// end of the file. So, before writing, save the current position (using
756 /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`), and restore it before the next read.
760 /// This function doesn't create the file if it doesn't exist. Use the [`create`]
763 /// [`write()`]: ../../std/fs/struct.File.html#method.write
764 /// [`flush()`]: ../../std/fs/struct.File.html#method.flush
765 /// [`seek`]: ../../std/fs/struct.File.html#method.seek
766 /// [`SeekFrom`]: ../../std/io/enum.SeekFrom.html
767 /// [`Current`]: ../../std/io/enum.SeekFrom.html#variant.Current
768 /// [`create`]: #method.create
773 /// use std::fs::OpenOptions;
775 /// let file = OpenOptions::new().append(true).open("foo.txt");
777 #[stable(feature = "rust1", since = "1.0.0")]
778 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
779 self.0.append(append); self
782 /// Sets the option for truncating a previous file.
784 /// If a file is successfully opened with this option set it will truncate
785 /// the file to 0 length if it already exists.
787 /// The file must be opened with write access for truncate to work.
792 /// use std::fs::OpenOptions;
794 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
796 #[stable(feature = "rust1", since = "1.0.0")]
797 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
798 self.0.truncate(truncate); self
801 /// Sets the option for creating a new file.
803 /// This option indicates whether a new file will be created if the file
804 /// does not yet already exist.
806 /// In order for the file to be created, [`write`] or [`append`] access must
809 /// [`write`]: #method.write
810 /// [`append`]: #method.append
815 /// use std::fs::OpenOptions;
817 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
819 #[stable(feature = "rust1", since = "1.0.0")]
820 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
821 self.0.create(create); self
824 /// Sets the option to always create a new file.
826 /// This option indicates whether a new file will be created.
827 /// No file is allowed to exist at the target location, also no (dangling)
830 /// This option is useful because it is atomic. Otherwise between checking
831 /// whether a file exists and creating a new one, the file may have been
832 /// created by another process (a TOCTOU race condition / attack).
834 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
837 /// The file must be opened with write or append access in order to create
840 /// [`.create()`]: #method.create
841 /// [`.truncate()`]: #method.truncate
846 /// use std::fs::OpenOptions;
848 /// let file = OpenOptions::new().write(true)
849 /// .create_new(true)
850 /// .open("foo.txt");
852 #[stable(feature = "expand_open_options2", since = "1.9.0")]
853 pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
854 self.0.create_new(create_new); self
857 /// Opens a file at `path` with the options specified by `self`.
861 /// This function will return an error under a number of different
862 /// circumstances. Some of these error conditions are listed here, together
863 /// with their [`ErrorKind`]. The mapping to [`ErrorKind`]s is not part of
864 /// the compatibility contract of the function, especially the `Other` kind
865 /// might change to more specific kinds in the future.
867 /// * [`NotFound`]: The specified file does not exist and neither `create`
868 /// or `create_new` is set.
869 /// * [`NotFound`]: One of the directory components of the file path does
871 /// * [`PermissionDenied`]: The user lacks permission to get the specified
872 /// access rights for the file.
873 /// * [`PermissionDenied`]: The user lacks permission to open one of the
874 /// directory components of the specified path.
875 /// * [`AlreadyExists`]: `create_new` was specified and the file already
877 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
878 /// without write access, no access mode set, etc.).
879 /// * [`Other`]: One of the directory components of the specified file path
880 /// was not, in fact, a directory.
881 /// * [`Other`]: Filesystem-level errors: full disk, write permission
882 /// requested on a read-only file system, exceeded disk quota, too many
883 /// open files, too long filename, too many symbolic links in the
884 /// specified path (Unix-like systems only), etc.
889 /// use std::fs::OpenOptions;
891 /// let file = OpenOptions::new().open("foo.txt");
894 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
895 /// [`AlreadyExists`]: ../io/enum.ErrorKind.html#variant.AlreadyExists
896 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
897 /// [`NotFound`]: ../io/enum.ErrorKind.html#variant.NotFound
898 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
899 /// [`PermissionDenied`]: ../io/enum.ErrorKind.html#variant.PermissionDenied
900 #[stable(feature = "rust1", since = "1.0.0")]
901 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
902 self._open(path.as_ref())
905 fn _open(&self, path: &Path) -> io::Result<File> {
906 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
910 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
911 fn as_inner(&self) -> &fs_imp::OpenOptions { &self.0 }
914 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
915 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
919 /// Returns the file type for this metadata.
924 /// fn main() -> std::io::Result<()> {
927 /// let metadata = fs::metadata("foo.txt")?;
929 /// println!("{:?}", metadata.file_type());
933 #[stable(feature = "file_type", since = "1.1.0")]
934 pub fn file_type(&self) -> FileType {
935 FileType(self.0.file_type())
938 /// Returns `true` if this metadata is for a directory. The
939 /// result is mutually exclusive to the result of
940 /// [`is_file`], and will be false for symlink metadata
941 /// obtained from [`symlink_metadata`].
943 /// [`is_file`]: struct.Metadata.html#method.is_file
944 /// [`symlink_metadata`]: fn.symlink_metadata.html
949 /// fn main() -> std::io::Result<()> {
952 /// let metadata = fs::metadata("foo.txt")?;
954 /// assert!(!metadata.is_dir());
958 #[stable(feature = "rust1", since = "1.0.0")]
959 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
961 /// Returns `true` if this metadata is for a regular file. The
962 /// result is mutually exclusive to the result of
963 /// [`is_dir`], and will be false for symlink metadata
964 /// obtained from [`symlink_metadata`].
966 /// [`is_dir`]: struct.Metadata.html#method.is_dir
967 /// [`symlink_metadata`]: fn.symlink_metadata.html
974 /// fn main() -> std::io::Result<()> {
975 /// let metadata = fs::metadata("foo.txt")?;
977 /// assert!(metadata.is_file());
981 #[stable(feature = "rust1", since = "1.0.0")]
982 pub fn is_file(&self) -> bool { self.file_type().is_file() }
984 /// Returns the size of the file, in bytes, this metadata is for.
991 /// fn main() -> std::io::Result<()> {
992 /// let metadata = fs::metadata("foo.txt")?;
994 /// assert_eq!(0, metadata.len());
998 #[stable(feature = "rust1", since = "1.0.0")]
999 pub fn len(&self) -> u64 { self.0.size() }
1001 /// Returns the permissions of the file this metadata is for.
1008 /// fn main() -> std::io::Result<()> {
1009 /// let metadata = fs::metadata("foo.txt")?;
1011 /// assert!(!metadata.permissions().readonly());
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 pub fn permissions(&self) -> Permissions {
1017 Permissions(self.0.perm())
1020 /// Returns the last modification time listed in this metadata.
1022 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1023 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1027 /// This field may not be available on all platforms, and will return an
1028 /// `Err` on platforms where it is not available.
1035 /// fn main() -> std::io::Result<()> {
1036 /// let metadata = fs::metadata("foo.txt")?;
1038 /// if let Ok(time) = metadata.modified() {
1039 /// println!("{:?}", time);
1041 /// println!("Not supported on this platform");
1046 #[stable(feature = "fs_time", since = "1.10.0")]
1047 pub fn modified(&self) -> io::Result<SystemTime> {
1048 self.0.modified().map(FromInner::from_inner)
1051 /// Returns the last access time of this metadata.
1053 /// The returned value corresponds to the `atime` field of `stat` on Unix
1054 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1056 /// Note that not all platforms will keep this field update in a file's
1057 /// metadata, for example Windows has an option to disable updating this
1058 /// time when files are accessed and Linux similarly has `noatime`.
1062 /// This field may not be available on all platforms, and will return an
1063 /// `Err` on platforms where it is not available.
1070 /// fn main() -> std::io::Result<()> {
1071 /// let metadata = fs::metadata("foo.txt")?;
1073 /// if let Ok(time) = metadata.accessed() {
1074 /// println!("{:?}", time);
1076 /// println!("Not supported on this platform");
1081 #[stable(feature = "fs_time", since = "1.10.0")]
1082 pub fn accessed(&self) -> io::Result<SystemTime> {
1083 self.0.accessed().map(FromInner::from_inner)
1086 /// Returns the creation time listed in this metadata.
1088 /// The returned value corresponds to the `birthtime` field of `stat` on
1089 /// Unix platforms and the `ftCreationTime` field on Windows platforms.
1093 /// This field may not be available on all platforms, and will return an
1094 /// `Err` on platforms where it is not available.
1101 /// fn main() -> std::io::Result<()> {
1102 /// let metadata = fs::metadata("foo.txt")?;
1104 /// if let Ok(time) = metadata.created() {
1105 /// println!("{:?}", time);
1107 /// println!("Not supported on this platform");
1112 #[stable(feature = "fs_time", since = "1.10.0")]
1113 pub fn created(&self) -> io::Result<SystemTime> {
1114 self.0.created().map(FromInner::from_inner)
1118 #[stable(feature = "std_debug", since = "1.16.0")]
1119 impl fmt::Debug for Metadata {
1120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1121 f.debug_struct("Metadata")
1122 .field("file_type", &self.file_type())
1123 .field("is_dir", &self.is_dir())
1124 .field("is_file", &self.is_file())
1125 .field("permissions", &self.permissions())
1126 .field("modified", &self.modified())
1127 .field("accessed", &self.accessed())
1128 .field("created", &self.created())
1133 impl AsInner<fs_imp::FileAttr> for Metadata {
1134 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
1137 impl FromInner<fs_imp::FileAttr> for Metadata {
1138 fn from_inner(attr: fs_imp::FileAttr) -> Metadata { Metadata(attr) }
1142 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1147 /// use std::fs::File;
1149 /// fn main() -> std::io::Result<()> {
1150 /// let mut f = File::create("foo.txt")?;
1151 /// let metadata = f.metadata()?;
1153 /// assert_eq!(false, metadata.permissions().readonly());
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 pub fn readonly(&self) -> bool { self.0.readonly() }
1160 /// Modifies the readonly flag for this set of permissions. If the
1161 /// `readonly` argument is `true`, using the resulting `Permission` will
1162 /// update file permissions to forbid writing. Conversely, if it's `false`,
1163 /// using the resulting `Permission` will update file permissions to allow
1166 /// This operation does **not** modify the filesystem. To modify the
1167 /// filesystem use the [`fs::set_permissions`] function.
1169 /// [`fs::set_permissions`]: fn.set_permissions.html
1174 /// use std::fs::File;
1176 /// fn main() -> std::io::Result<()> {
1177 /// let f = File::create("foo.txt")?;
1178 /// let metadata = f.metadata()?;
1179 /// let mut permissions = metadata.permissions();
1181 /// permissions.set_readonly(true);
1183 /// // filesystem doesn't change
1184 /// assert_eq!(false, metadata.permissions().readonly());
1186 /// // just this particular `permissions`.
1187 /// assert_eq!(true, permissions.readonly());
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 pub fn set_readonly(&mut self, readonly: bool) {
1193 self.0.set_readonly(readonly)
1198 /// Tests whether this file type represents a directory. The
1199 /// result is mutually exclusive to the results of
1200 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1203 /// [`is_file`]: struct.FileType.html#method.is_file
1204 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1209 /// fn main() -> std::io::Result<()> {
1212 /// let metadata = fs::metadata("foo.txt")?;
1213 /// let file_type = metadata.file_type();
1215 /// assert_eq!(file_type.is_dir(), false);
1219 #[stable(feature = "file_type", since = "1.1.0")]
1220 pub fn is_dir(&self) -> bool { self.0.is_dir() }
1222 /// Tests whether this file type represents a regular file.
1223 /// The result is mutually exclusive to the results of
1224 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1227 /// [`is_dir`]: struct.FileType.html#method.is_dir
1228 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1233 /// fn main() -> std::io::Result<()> {
1236 /// let metadata = fs::metadata("foo.txt")?;
1237 /// let file_type = metadata.file_type();
1239 /// assert_eq!(file_type.is_file(), true);
1243 #[stable(feature = "file_type", since = "1.1.0")]
1244 pub fn is_file(&self) -> bool { self.0.is_file() }
1246 /// Tests whether this file type represents a symbolic link.
1247 /// The result is mutually exclusive to the results of
1248 /// [`is_dir`] and [`is_file`]; only zero or one of these
1251 /// The underlying [`Metadata`] struct needs to be retrieved
1252 /// with the [`fs::symlink_metadata`] function and not the
1253 /// [`fs::metadata`] function. The [`fs::metadata`] function
1254 /// follows symbolic links, so [`is_symlink`] would always
1255 /// return `false` for the target file.
1257 /// [`Metadata`]: struct.Metadata.html
1258 /// [`fs::metadata`]: fn.metadata.html
1259 /// [`fs::symlink_metadata`]: fn.symlink_metadata.html
1260 /// [`is_dir`]: struct.FileType.html#method.is_dir
1261 /// [`is_file`]: struct.FileType.html#method.is_file
1262 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1269 /// fn main() -> std::io::Result<()> {
1270 /// let metadata = fs::symlink_metadata("foo.txt")?;
1271 /// let file_type = metadata.file_type();
1273 /// assert_eq!(file_type.is_symlink(), false);
1277 #[stable(feature = "file_type", since = "1.1.0")]
1278 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
1281 impl AsInner<fs_imp::FileType> for FileType {
1282 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
1285 impl FromInner<fs_imp::FilePermissions> for Permissions {
1286 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1291 impl AsInner<fs_imp::FilePermissions> for Permissions {
1292 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
1295 #[stable(feature = "rust1", since = "1.0.0")]
1296 impl Iterator for ReadDir {
1297 type Item = io::Result<DirEntry>;
1299 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1300 self.0.next().map(|entry| entry.map(DirEntry))
1305 /// Returns the full path to the file that this entry represents.
1307 /// The full path is created by joining the original path to `read_dir`
1308 /// with the filename of this entry.
1315 /// fn main() -> std::io::Result<()> {
1316 /// for entry in fs::read_dir(".")? {
1317 /// let dir = entry?;
1318 /// println!("{:?}", dir.path());
1324 /// This prints output like:
1327 /// "./whatever.txt"
1329 /// "./hello_world.rs"
1332 /// The exact text, of course, depends on what files you have in `.`.
1333 #[stable(feature = "rust1", since = "1.0.0")]
1334 pub fn path(&self) -> PathBuf { self.0.path() }
1336 /// Returns the metadata for the file that this entry points at.
1338 /// This function will not traverse symlinks if this entry points at a
1341 /// # Platform-specific behavior
1343 /// On Windows this function is cheap to call (no extra system calls
1344 /// needed), but on Unix platforms this function is the equivalent of
1345 /// calling `symlink_metadata` on the path.
1352 /// if let Ok(entries) = fs::read_dir(".") {
1353 /// for entry in entries {
1354 /// if let Ok(entry) = entry {
1355 /// // Here, `entry` is a `DirEntry`.
1356 /// if let Ok(metadata) = entry.metadata() {
1357 /// // Now let's show our entry's permissions!
1358 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1360 /// println!("Couldn't get metadata for {:?}", entry.path());
1366 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1367 pub fn metadata(&self) -> io::Result<Metadata> {
1368 self.0.metadata().map(Metadata)
1371 /// Returns the file type for the file that this entry points at.
1373 /// This function will not traverse symlinks if this entry points at a
1376 /// # Platform-specific behavior
1378 /// On Windows and most Unix platforms this function is free (no extra
1379 /// system calls needed), but some Unix platforms may require the equivalent
1380 /// call to `symlink_metadata` to learn about the target file type.
1387 /// if let Ok(entries) = fs::read_dir(".") {
1388 /// for entry in entries {
1389 /// if let Ok(entry) = entry {
1390 /// // Here, `entry` is a `DirEntry`.
1391 /// if let Ok(file_type) = entry.file_type() {
1392 /// // Now let's show our entry's file type!
1393 /// println!("{:?}: {:?}", entry.path(), file_type);
1395 /// println!("Couldn't get file type for {:?}", entry.path());
1401 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1402 pub fn file_type(&self) -> io::Result<FileType> {
1403 self.0.file_type().map(FileType)
1406 /// Returns the bare file name of this directory entry without any other
1407 /// leading path component.
1414 /// if let Ok(entries) = fs::read_dir(".") {
1415 /// for entry in entries {
1416 /// if let Ok(entry) = entry {
1417 /// // Here, `entry` is a `DirEntry`.
1418 /// println!("{:?}", entry.file_name());
1423 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1424 pub fn file_name(&self) -> OsString {
1429 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1430 impl fmt::Debug for DirEntry {
1431 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1432 f.debug_tuple("DirEntry")
1433 .field(&self.path())
1438 impl AsInner<fs_imp::DirEntry> for DirEntry {
1439 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
1442 /// Removes a file from the filesystem.
1444 /// Note that there is no
1445 /// guarantee that the file is immediately deleted (e.g., depending on
1446 /// platform, other open file descriptors may prevent immediate removal).
1448 /// # Platform-specific behavior
1450 /// This function currently corresponds to the `unlink` function on Unix
1451 /// and the `DeleteFile` function on Windows.
1452 /// Note that, this [may change in the future][changes].
1454 /// [changes]: ../io/index.html#platform-specific-behavior
1458 /// This function will return an error in the following situations, but is not
1459 /// limited to just these cases:
1461 /// * `path` points to a directory.
1462 /// * The user lacks permissions to remove the file.
1469 /// fn main() -> std::io::Result<()> {
1470 /// fs::remove_file("a.txt")?;
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1476 fs_imp::unlink(path.as_ref())
1479 /// Given a path, query the file system to get information about a file,
1482 /// This function will traverse symbolic links to query information about the
1483 /// destination file.
1485 /// # Platform-specific behavior
1487 /// This function currently corresponds to the `stat` 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::metadata("/some/file/path.txt")?;
1508 /// // inspect attr ...
1512 #[stable(feature = "rust1", since = "1.0.0")]
1513 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1514 fs_imp::stat(path.as_ref()).map(Metadata)
1517 /// Query the metadata about a file without following symlinks.
1519 /// # Platform-specific behavior
1521 /// This function currently corresponds to the `lstat` function on Unix
1522 /// and the `GetFileAttributesEx` function on Windows.
1523 /// Note that, this [may change in the future][changes].
1525 /// [changes]: ../io/index.html#platform-specific-behavior
1529 /// This function will return an error in the following situations, but is not
1530 /// limited to just these cases:
1532 /// * The user lacks permissions to perform `metadata` call on `path`.
1533 /// * `path` does not exist.
1540 /// fn main() -> std::io::Result<()> {
1541 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1542 /// // inspect attr ...
1546 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1547 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1548 fs_imp::lstat(path.as_ref()).map(Metadata)
1551 /// Rename a file or directory to a new name, replacing the original file if
1552 /// `to` already exists.
1554 /// This will not work if the new name is on a different mount point.
1556 /// # Platform-specific behavior
1558 /// This function currently corresponds to the `rename` function on Unix
1559 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1561 /// Because of this, the behavior when both `from` and `to` exist differs. On
1562 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1563 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1564 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1566 /// Note that, this [may change in the future][changes].
1568 /// [changes]: ../io/index.html#platform-specific-behavior
1572 /// This function will return an error in the following situations, but is not
1573 /// limited to just these cases:
1575 /// * `from` does not exist.
1576 /// * The user lacks permissions to view contents.
1577 /// * `from` and `to` are on separate filesystems.
1584 /// fn main() -> std::io::Result<()> {
1585 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1589 #[stable(feature = "rust1", since = "1.0.0")]
1590 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1591 fs_imp::rename(from.as_ref(), to.as_ref())
1594 /// Copies the contents of one file to another. This function will also
1595 /// copy the permission bits of the original file to the destination file.
1597 /// This function will **overwrite** the contents of `to`.
1599 /// Note that if `from` and `to` both point to the same file, then the file
1600 /// will likely get truncated by this operation.
1602 /// On success, the total number of bytes copied is returned and it is equal to
1603 /// the length of the `to` file as reported by `metadata`.
1605 /// If you’re wanting to copy the contents of one file to another and you’re
1606 /// working with [`File`]s, see the [`io::copy`] function.
1608 /// [`io::copy`]: ../io/fn.copy.html
1609 /// [`File`]: ./struct.File.html
1611 /// # Platform-specific behavior
1613 /// This function currently corresponds to the `open` function in Unix
1614 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1615 /// `O_CLOEXEC` is set for returned file descriptors.
1616 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1617 /// NTFS streams are copied but only the size of the main stream is returned by
1618 /// this function. On MacOS, this function corresponds to `copyfile` with
1620 /// Note that, this [may change in the future][changes].
1622 /// [changes]: ../io/index.html#platform-specific-behavior
1626 /// This function will return an error in the following situations, but is not
1627 /// limited to just these cases:
1629 /// * The `from` path is not a file.
1630 /// * The `from` file does not exist.
1631 /// * The current process does not have the permission rights to access
1632 /// `from` or write `to`.
1639 /// fn main() -> std::io::Result<()> {
1640 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1646 fs_imp::copy(from.as_ref(), to.as_ref())
1649 /// Creates a new hard link on the filesystem.
1651 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1652 /// often require these two paths to both be located on the same filesystem.
1654 /// # Platform-specific behavior
1656 /// This function currently corresponds to the `link` function on Unix
1657 /// and the `CreateHardLink` function on Windows.
1658 /// Note that, this [may change in the future][changes].
1660 /// [changes]: ../io/index.html#platform-specific-behavior
1664 /// This function will return an error in the following situations, but is not
1665 /// limited to just these cases:
1667 /// * The `src` path is not a file or doesn't exist.
1674 /// fn main() -> std::io::Result<()> {
1675 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1679 #[stable(feature = "rust1", since = "1.0.0")]
1680 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1681 fs_imp::link(src.as_ref(), dst.as_ref())
1684 /// Creates a new symbolic link on the filesystem.
1686 /// The `dst` path will be a symbolic link pointing to the `src` path.
1687 /// On Windows, this will be a file symlink, not a directory symlink;
1688 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1689 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1690 /// used instead to make the intent explicit.
1692 /// [`std::os::unix::fs::symlink`]: ../os/unix/fs/fn.symlink.html
1693 /// [`std::os::windows::fs::symlink_file`]: ../os/windows/fs/fn.symlink_file.html
1694 /// [`symlink_dir`]: ../os/windows/fs/fn.symlink_dir.html
1702 /// fn main() -> std::io::Result<()> {
1703 /// fs::soft_link("a.txt", "b.txt")?;
1707 #[stable(feature = "rust1", since = "1.0.0")]
1708 #[rustc_deprecated(since = "1.1.0",
1709 reason = "replaced with std::os::unix::fs::symlink and \
1710 std::os::windows::fs::{symlink_file, symlink_dir}")]
1711 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1712 fs_imp::symlink(src.as_ref(), dst.as_ref())
1715 /// Reads a symbolic link, returning the file that the link points to.
1717 /// # Platform-specific behavior
1719 /// This function currently corresponds to the `readlink` function on Unix
1720 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1721 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1722 /// Note that, this [may change in the future][changes].
1724 /// [changes]: ../io/index.html#platform-specific-behavior
1728 /// This function will return an error in the following situations, but is not
1729 /// limited to just these cases:
1731 /// * `path` is not a symbolic link.
1732 /// * `path` does not exist.
1739 /// fn main() -> std::io::Result<()> {
1740 /// let path = fs::read_link("a.txt")?;
1744 #[stable(feature = "rust1", since = "1.0.0")]
1745 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1746 fs_imp::readlink(path.as_ref())
1749 /// Returns the canonical, absolute form of a path with all intermediate
1750 /// components normalized and symbolic links resolved.
1752 /// # Platform-specific behavior
1754 /// This function currently corresponds to the `realpath` function on Unix
1755 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1756 /// Note that, this [may change in the future][changes].
1758 /// On Windows, this converts the path to use [extended length path][path]
1759 /// syntax, which allows your program to use longer path names, but means you
1760 /// can only join backslash-delimited paths to it, and it may be incompatible
1761 /// with other applications (if passed to the application on the command-line,
1762 /// or written to a file another application may read).
1764 /// [changes]: ../io/index.html#platform-specific-behavior
1765 /// [path]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
1769 /// This function will return an error in the following situations, but is not
1770 /// limited to just these cases:
1772 /// * `path` does not exist.
1773 /// * A non-final component in path is not a directory.
1780 /// fn main() -> std::io::Result<()> {
1781 /// let path = fs::canonicalize("../a/../foo.txt")?;
1785 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1786 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1787 fs_imp::canonicalize(path.as_ref())
1790 /// Creates a new, empty directory at the provided path
1792 /// # Platform-specific behavior
1794 /// This function currently corresponds to the `mkdir` function on Unix
1795 /// and the `CreateDirectory` function on Windows.
1796 /// Note that, this [may change in the future][changes].
1798 /// [changes]: ../io/index.html#platform-specific-behavior
1800 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1801 /// return an error. To create a directory and all its missing parents at the
1802 /// same time, use the [`create_dir_all`] function.
1806 /// This function will return an error in the following situations, but is not
1807 /// limited to just these cases:
1809 /// * User lacks permissions to create directory at `path`.
1810 /// * A parent of the given path doesn't exist. (To create a directory and all
1811 /// its missing parents at the same time, use the [`create_dir_all`]
1813 /// * `path` already exists.
1820 /// fn main() -> std::io::Result<()> {
1821 /// fs::create_dir("/some/dir")?;
1825 #[stable(feature = "rust1", since = "1.0.0")]
1826 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1827 DirBuilder::new().create(path.as_ref())
1830 /// Recursively create a directory and all of its parent components if they
1833 /// # Platform-specific behavior
1835 /// This function currently corresponds to the `mkdir` function on Unix
1836 /// and the `CreateDirectory` function on Windows.
1837 /// Note that, this [may change in the future][changes].
1839 /// [changes]: ../io/index.html#platform-specific-behavior
1843 /// This function will return an error in the following situations, but is not
1844 /// limited to just these cases:
1846 /// * If any directory in the path specified by `path`
1847 /// does not already exist and it could not be created otherwise. The specific
1848 /// error conditions for when a directory is being created (after it is
1849 /// determined to not exist) are outlined by [`fs::create_dir`].
1851 /// Notable exception is made for situations where any of the directories
1852 /// specified in the `path` could not be created as it was being created concurrently.
1853 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1854 /// concurrently from multiple threads or processes is guaranteed not to fail
1855 /// due to a race condition with itself.
1857 /// [`fs::create_dir`]: fn.create_dir.html
1864 /// fn main() -> std::io::Result<()> {
1865 /// fs::create_dir_all("/some/dir")?;
1869 #[stable(feature = "rust1", since = "1.0.0")]
1870 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1871 DirBuilder::new().recursive(true).create(path.as_ref())
1874 /// Removes an existing, empty directory.
1876 /// # Platform-specific behavior
1878 /// This function currently corresponds to the `rmdir` function on Unix
1879 /// and the `RemoveDirectory` function on Windows.
1880 /// Note that, this [may change in the future][changes].
1882 /// [changes]: ../io/index.html#platform-specific-behavior
1886 /// This function will return an error in the following situations, but is not
1887 /// limited to just these cases:
1889 /// * The user lacks permissions to remove the directory at the provided `path`.
1890 /// * The directory isn't empty.
1897 /// fn main() -> std::io::Result<()> {
1898 /// fs::remove_dir("/some/dir")?;
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1904 fs_imp::rmdir(path.as_ref())
1907 /// Removes a directory at this path, after removing all its contents. Use
1910 /// This function does **not** follow symbolic links and it will simply remove the
1911 /// symbolic link itself.
1913 /// # Platform-specific behavior
1915 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1916 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1918 /// Note that, this [may change in the future][changes].
1920 /// [changes]: ../io/index.html#platform-specific-behavior
1924 /// See [`fs::remove_file`] and [`fs::remove_dir`].
1926 /// [`fs::remove_file`]: fn.remove_file.html
1927 /// [`fs::remove_dir`]: fn.remove_dir.html
1934 /// fn main() -> std::io::Result<()> {
1935 /// fs::remove_dir_all("/some/dir")?;
1939 #[stable(feature = "rust1", since = "1.0.0")]
1940 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1941 fs_imp::remove_dir_all(path.as_ref())
1944 /// Returns an iterator over the entries within a directory.
1946 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
1947 /// New errors may be encountered after an iterator is initially constructed.
1949 /// [`io::Result`]: ../io/type.Result.html
1950 /// [`DirEntry`]: struct.DirEntry.html
1952 /// # Platform-specific behavior
1954 /// This function currently corresponds to the `opendir` function on Unix
1955 /// and the `FindFirstFile` function on Windows.
1956 /// Note that, this [may change in the future][changes].
1958 /// [changes]: ../io/index.html#platform-specific-behavior
1962 /// This function will return an error in the following situations, but is not
1963 /// limited to just these cases:
1965 /// * The provided `path` doesn't exist.
1966 /// * The process lacks permissions to view the contents.
1967 /// * The `path` points at a non-directory file.
1973 /// use std::fs::{self, DirEntry};
1974 /// use std::path::Path;
1976 /// // one possible implementation of walking a directory only visiting files
1977 /// fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> {
1978 /// if dir.is_dir() {
1979 /// for entry in fs::read_dir(dir)? {
1980 /// let entry = entry?;
1981 /// let path = entry.path();
1982 /// if path.is_dir() {
1983 /// visit_dirs(&path, cb)?;
1992 #[stable(feature = "rust1", since = "1.0.0")]
1993 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
1994 fs_imp::readdir(path.as_ref()).map(ReadDir)
1997 /// Changes the permissions found on a file or a directory.
1999 /// # Platform-specific behavior
2001 /// This function currently corresponds to the `chmod` function on Unix
2002 /// and the `SetFileAttributes` function on Windows.
2003 /// Note that, this [may change in the future][changes].
2005 /// [changes]: ../io/index.html#platform-specific-behavior
2009 /// This function will return an error in the following situations, but is not
2010 /// limited to just these cases:
2012 /// * `path` does not exist.
2013 /// * The user lacks the permission to change attributes of the file.
2020 /// fn main() -> std::io::Result<()> {
2021 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2022 /// perms.set_readonly(true);
2023 /// fs::set_permissions("foo.txt", perms)?;
2027 #[stable(feature = "set_permissions", since = "1.1.0")]
2028 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
2030 fs_imp::set_perm(path.as_ref(), perm.0)
2034 /// Creates a new set of options with default mode/security settings for all
2035 /// platforms and also non-recursive.
2040 /// use std::fs::DirBuilder;
2042 /// let builder = DirBuilder::new();
2044 #[stable(feature = "dir_builder", since = "1.6.0")]
2045 pub fn new() -> DirBuilder {
2047 inner: fs_imp::DirBuilder::new(),
2052 /// Indicates that directories should be created recursively, creating all
2053 /// parent directories. Parents that do not exist are created with the same
2054 /// security and permissions settings.
2056 /// This option defaults to `false`.
2061 /// use std::fs::DirBuilder;
2063 /// let mut builder = DirBuilder::new();
2064 /// builder.recursive(true);
2066 #[stable(feature = "dir_builder", since = "1.6.0")]
2067 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2068 self.recursive = recursive;
2072 /// Creates the specified directory with the options configured in this
2075 /// It is considered an error if the directory already exists unless
2076 /// recursive mode is enabled.
2081 /// use std::fs::{self, DirBuilder};
2083 /// let path = "/tmp/foo/bar/baz";
2084 /// DirBuilder::new()
2085 /// .recursive(true)
2086 /// .create(path).unwrap();
2088 /// assert!(fs::metadata(path).unwrap().is_dir());
2090 #[stable(feature = "dir_builder", since = "1.6.0")]
2091 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2092 self._create(path.as_ref())
2095 fn _create(&self, path: &Path) -> io::Result<()> {
2097 self.create_dir_all(path)
2099 self.inner.mkdir(path)
2103 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2104 if path == Path::new("") {
2108 match self.inner.mkdir(path) {
2109 Ok(()) => return Ok(()),
2110 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2111 Err(_) if path.is_dir() => return Ok(()),
2112 Err(e) => return Err(e),
2114 match path.parent() {
2115 Some(p) => self.create_dir_all(p)?,
2116 None => return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree")),
2118 match self.inner.mkdir(path) {
2120 Err(_) if path.is_dir() => Ok(()),
2126 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2127 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2132 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
2134 use crate::io::prelude::*;
2136 use crate::fs::{self, File, OpenOptions};
2137 use crate::io::{ErrorKind, SeekFrom};
2138 use crate::path::Path;
2140 use crate::sys_common::io::test::{TempDir, tmpdir};
2143 use rand::{rngs::StdRng, FromEntropy, RngCore};
2146 use crate::os::windows::fs::{symlink_dir, symlink_file};
2148 use crate::sys::fs::symlink_junction;
2150 use crate::os::unix::fs::symlink as symlink_dir;
2152 use crate::os::unix::fs::symlink as symlink_file;
2154 use crate::os::unix::fs::symlink as symlink_junction;
2156 macro_rules! check { ($e:expr) => (
2159 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
2164 macro_rules! error { ($e:expr, $s:expr) => (
2166 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2167 Err(ref err) => assert!(err.raw_os_error() == Some($s),
2168 format!("`{}` did not have a code of `{}`", err, $s))
2173 macro_rules! error { ($e:expr, $s:expr) => ( error_contains!($e, $s) ) }
2175 macro_rules! error_contains { ($e:expr, $s:expr) => (
2177 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2178 Err(ref err) => assert!(err.to_string().contains($s),
2179 format!("`{}` did not contain `{}`", err, $s))
2183 // Several test fail on windows if the user does not have permission to
2184 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
2185 // disabling these test on Windows, use this function to test whether we
2186 // have permission, and return otherwise. This way, we still don't run these
2187 // tests most of the time, but at least we do if the user has the right
2189 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
2190 if cfg!(unix) { return true }
2191 let link = tmpdir.join("some_hopefully_unique_link_name");
2193 match symlink_file(r"nonexisting_target", link) {
2195 // ERROR_PRIVILEGE_NOT_HELD = 1314
2196 Err(ref err) if err.raw_os_error() == Some(1314) => false,
2202 fn file_test_io_smoke_test() {
2203 let message = "it's alright. have a good time";
2204 let tmpdir = tmpdir();
2205 let filename = &tmpdir.join("file_rt_io_file_test.txt");
2207 let mut write_stream = check!(File::create(filename));
2208 check!(write_stream.write(message.as_bytes()));
2211 let mut read_stream = check!(File::open(filename));
2212 let mut read_buf = [0; 1028];
2213 let read_str = match check!(read_stream.read(&mut read_buf)) {
2214 0 => panic!("shouldn't happen"),
2215 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
2217 assert_eq!(read_str, message);
2219 check!(fs::remove_file(filename));
2223 fn invalid_path_raises() {
2224 let tmpdir = tmpdir();
2225 let filename = &tmpdir.join("file_that_does_not_exist.txt");
2226 let result = File::open(filename);
2229 error!(result, "No such file or directory");
2231 error!(result, 2); // ERROR_FILE_NOT_FOUND
2235 fn file_test_iounlinking_invalid_path_should_raise_condition() {
2236 let tmpdir = tmpdir();
2237 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
2239 let result = fs::remove_file(filename);
2242 error!(result, "No such file or directory");
2244 error!(result, 2); // ERROR_FILE_NOT_FOUND
2248 fn file_test_io_non_positional_read() {
2249 let message: &str = "ten-four";
2250 let mut read_mem = [0; 8];
2251 let tmpdir = tmpdir();
2252 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
2254 let mut rw_stream = check!(File::create(filename));
2255 check!(rw_stream.write(message.as_bytes()));
2258 let mut read_stream = check!(File::open(filename));
2260 let read_buf = &mut read_mem[0..4];
2261 check!(read_stream.read(read_buf));
2264 let read_buf = &mut read_mem[4..8];
2265 check!(read_stream.read(read_buf));
2268 check!(fs::remove_file(filename));
2269 let read_str = str::from_utf8(&read_mem).unwrap();
2270 assert_eq!(read_str, message);
2274 fn file_test_io_seek_and_tell_smoke_test() {
2275 let message = "ten-four";
2276 let mut read_mem = [0; 4];
2277 let set_cursor = 4 as u64;
2278 let tell_pos_pre_read;
2279 let tell_pos_post_read;
2280 let tmpdir = tmpdir();
2281 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
2283 let mut rw_stream = check!(File::create(filename));
2284 check!(rw_stream.write(message.as_bytes()));
2287 let mut read_stream = check!(File::open(filename));
2288 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
2289 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
2290 check!(read_stream.read(&mut read_mem));
2291 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
2293 check!(fs::remove_file(filename));
2294 let read_str = str::from_utf8(&read_mem).unwrap();
2295 assert_eq!(read_str, &message[4..8]);
2296 assert_eq!(tell_pos_pre_read, set_cursor);
2297 assert_eq!(tell_pos_post_read, message.len() as u64);
2301 fn file_test_io_seek_and_write() {
2302 let initial_msg = "food-is-yummy";
2303 let overwrite_msg = "-the-bar!!";
2304 let final_msg = "foo-the-bar!!";
2306 let mut read_mem = [0; 13];
2307 let tmpdir = tmpdir();
2308 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
2310 let mut rw_stream = check!(File::create(filename));
2311 check!(rw_stream.write(initial_msg.as_bytes()));
2312 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
2313 check!(rw_stream.write(overwrite_msg.as_bytes()));
2316 let mut read_stream = check!(File::open(filename));
2317 check!(read_stream.read(&mut read_mem));
2319 check!(fs::remove_file(filename));
2320 let read_str = str::from_utf8(&read_mem).unwrap();
2321 assert!(read_str == final_msg);
2325 fn file_test_io_seek_shakedown() {
2327 let initial_msg = "qwer-asdf-zxcv";
2328 let chunk_one: &str = "qwer";
2329 let chunk_two: &str = "asdf";
2330 let chunk_three: &str = "zxcv";
2331 let mut read_mem = [0; 4];
2332 let tmpdir = tmpdir();
2333 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2335 let mut rw_stream = check!(File::create(filename));
2336 check!(rw_stream.write(initial_msg.as_bytes()));
2339 let mut read_stream = check!(File::open(filename));
2341 check!(read_stream.seek(SeekFrom::End(-4)));
2342 check!(read_stream.read(&mut read_mem));
2343 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2345 check!(read_stream.seek(SeekFrom::Current(-9)));
2346 check!(read_stream.read(&mut read_mem));
2347 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2349 check!(read_stream.seek(SeekFrom::Start(0)));
2350 check!(read_stream.read(&mut read_mem));
2351 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2353 check!(fs::remove_file(filename));
2357 fn file_test_io_eof() {
2358 let tmpdir = tmpdir();
2359 let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2360 let mut buf = [0; 256];
2362 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2363 let mut rw = check!(oo.open(&filename));
2364 assert_eq!(check!(rw.read(&mut buf)), 0);
2365 assert_eq!(check!(rw.read(&mut buf)), 0);
2367 check!(fs::remove_file(&filename));
2372 fn file_test_io_read_write_at() {
2373 use crate::os::unix::fs::FileExt;
2375 let tmpdir = tmpdir();
2376 let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2377 let mut buf = [0; 256];
2378 let write1 = "asdf";
2379 let write2 = "qwer-";
2380 let write3 = "-zxcv";
2381 let content = "qwer-asdf-zxcv";
2383 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2384 let mut rw = check!(oo.open(&filename));
2385 assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2386 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2387 assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2388 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2389 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2390 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2391 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2392 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2393 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2394 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2395 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2396 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2397 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2398 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2399 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2400 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2401 assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2402 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2405 let mut read = check!(File::open(&filename));
2406 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2407 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2408 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2409 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2410 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2411 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2412 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2413 assert_eq!(check!(read.read(&mut buf)), write3.len());
2414 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2415 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2416 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2417 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2418 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2419 assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2420 assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2421 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2423 check!(fs::remove_file(&filename));
2428 fn set_get_unix_permissions() {
2429 use crate::os::unix::fs::PermissionsExt;
2431 let tmpdir = tmpdir();
2432 let filename = &tmpdir.join("set_get_unix_permissions");
2433 check!(fs::create_dir(filename));
2436 check!(fs::set_permissions(filename,
2437 fs::Permissions::from_mode(0)));
2438 let metadata0 = check!(fs::metadata(filename));
2439 assert_eq!(mask & metadata0.permissions().mode(), 0);
2441 check!(fs::set_permissions(filename,
2442 fs::Permissions::from_mode(0o1777)));
2443 let metadata1 = check!(fs::metadata(filename));
2444 assert_eq!(mask & metadata1.permissions().mode(), 0o1777);
2449 fn file_test_io_seek_read_write() {
2450 use crate::os::windows::fs::FileExt;
2452 let tmpdir = tmpdir();
2453 let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2454 let mut buf = [0; 256];
2455 let write1 = "asdf";
2456 let write2 = "qwer-";
2457 let write3 = "-zxcv";
2458 let content = "qwer-asdf-zxcv";
2460 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2461 let mut rw = check!(oo.open(&filename));
2462 assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2463 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2464 assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2465 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2466 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2467 assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2468 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2469 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2470 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2471 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2472 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2473 assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2474 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2475 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2476 assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2477 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2480 let mut read = check!(File::open(&filename));
2481 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2482 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2483 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2484 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2485 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2486 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2487 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2488 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2489 assert_eq!(check!(read.read(&mut buf)), write3.len());
2490 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2491 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2492 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2493 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2494 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2495 assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2496 assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2498 check!(fs::remove_file(&filename));
2502 fn file_test_stat_is_correct_on_is_file() {
2503 let tmpdir = tmpdir();
2504 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2506 let mut opts = OpenOptions::new();
2507 let mut fs = check!(opts.read(true).write(true)
2508 .create(true).open(filename));
2510 fs.write(msg.as_bytes()).unwrap();
2512 let fstat_res = check!(fs.metadata());
2513 assert!(fstat_res.is_file());
2515 let stat_res_fn = check!(fs::metadata(filename));
2516 assert!(stat_res_fn.is_file());
2517 let stat_res_meth = check!(filename.metadata());
2518 assert!(stat_res_meth.is_file());
2519 check!(fs::remove_file(filename));
2523 fn file_test_stat_is_correct_on_is_dir() {
2524 let tmpdir = tmpdir();
2525 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2526 check!(fs::create_dir(filename));
2527 let stat_res_fn = check!(fs::metadata(filename));
2528 assert!(stat_res_fn.is_dir());
2529 let stat_res_meth = check!(filename.metadata());
2530 assert!(stat_res_meth.is_dir());
2531 check!(fs::remove_dir(filename));
2535 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2536 let tmpdir = tmpdir();
2537 let dir = &tmpdir.join("fileinfo_false_on_dir");
2538 check!(fs::create_dir(dir));
2539 assert!(!dir.is_file());
2540 check!(fs::remove_dir(dir));
2544 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2545 let tmpdir = tmpdir();
2546 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2547 check!(check!(File::create(file)).write(b"foo"));
2548 assert!(file.exists());
2549 check!(fs::remove_file(file));
2550 assert!(!file.exists());
2554 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2555 let tmpdir = tmpdir();
2556 let dir = &tmpdir.join("before_and_after_dir");
2557 assert!(!dir.exists());
2558 check!(fs::create_dir(dir));
2559 assert!(dir.exists());
2560 assert!(dir.is_dir());
2561 check!(fs::remove_dir(dir));
2562 assert!(!dir.exists());
2566 fn file_test_directoryinfo_readdir() {
2567 let tmpdir = tmpdir();
2568 let dir = &tmpdir.join("di_readdir");
2569 check!(fs::create_dir(dir));
2572 let f = dir.join(&format!("{}.txt", n));
2573 let mut w = check!(File::create(&f));
2574 let msg_str = format!("{}{}", prefix, n.to_string());
2575 let msg = msg_str.as_bytes();
2576 check!(w.write(msg));
2578 let files = check!(fs::read_dir(dir));
2579 let mut mem = [0; 4];
2581 let f = f.unwrap().path();
2583 let n = f.file_stem().unwrap();
2584 check!(check!(File::open(&f)).read(&mut mem));
2585 let read_str = str::from_utf8(&mem).unwrap();
2586 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2587 assert_eq!(expected, read_str);
2589 check!(fs::remove_file(&f));
2591 check!(fs::remove_dir(dir));
2595 fn file_create_new_already_exists_error() {
2596 let tmpdir = tmpdir();
2597 let file = &tmpdir.join("file_create_new_error_exists");
2598 check!(fs::File::create(file));
2599 let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2600 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2604 fn mkdir_path_already_exists_error() {
2605 let tmpdir = tmpdir();
2606 let dir = &tmpdir.join("mkdir_error_twice");
2607 check!(fs::create_dir(dir));
2608 let e = fs::create_dir(dir).unwrap_err();
2609 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2613 fn recursive_mkdir() {
2614 let tmpdir = tmpdir();
2615 let dir = tmpdir.join("d1/d2");
2616 check!(fs::create_dir_all(&dir));
2617 assert!(dir.is_dir())
2621 fn recursive_mkdir_failure() {
2622 let tmpdir = tmpdir();
2623 let dir = tmpdir.join("d1");
2624 let file = dir.join("f1");
2626 check!(fs::create_dir_all(&dir));
2627 check!(File::create(&file));
2629 let result = fs::create_dir_all(&file);
2631 assert!(result.is_err());
2635 fn concurrent_recursive_mkdir() {
2638 let mut dir = dir.join("a");
2640 dir = dir.join("a");
2642 let mut join = vec!();
2644 let dir = dir.clone();
2645 join.push(thread::spawn(move || {
2646 check!(fs::create_dir_all(&dir));
2650 // No `Display` on result of `join()`
2651 join.drain(..).map(|join| join.join().unwrap()).count();
2656 fn recursive_mkdir_slash() {
2657 check!(fs::create_dir_all(Path::new("/")));
2661 fn recursive_mkdir_dot() {
2662 check!(fs::create_dir_all(Path::new(".")));
2666 fn recursive_mkdir_empty() {
2667 check!(fs::create_dir_all(Path::new("")));
2671 fn recursive_rmdir() {
2672 let tmpdir = tmpdir();
2673 let d1 = tmpdir.join("d1");
2674 let dt = d1.join("t");
2675 let dtt = dt.join("t");
2676 let d2 = tmpdir.join("d2");
2677 let canary = d2.join("do_not_delete");
2678 check!(fs::create_dir_all(&dtt));
2679 check!(fs::create_dir_all(&d2));
2680 check!(check!(File::create(&canary)).write(b"foo"));
2681 check!(symlink_junction(&d2, &dt.join("d2")));
2682 let _ = symlink_file(&canary, &d1.join("canary"));
2683 check!(fs::remove_dir_all(&d1));
2685 assert!(!d1.is_dir());
2686 assert!(canary.exists());
2690 fn recursive_rmdir_of_symlink() {
2691 // test we do not recursively delete a symlink but only dirs.
2692 let tmpdir = tmpdir();
2693 let link = tmpdir.join("d1");
2694 let dir = tmpdir.join("d2");
2695 let canary = dir.join("do_not_delete");
2696 check!(fs::create_dir_all(&dir));
2697 check!(check!(File::create(&canary)).write(b"foo"));
2698 check!(symlink_junction(&dir, &link));
2699 check!(fs::remove_dir_all(&link));
2701 assert!(!link.is_dir());
2702 assert!(canary.exists());
2706 // only Windows makes a distinction between file and directory symlinks.
2708 fn recursive_rmdir_of_file_symlink() {
2709 let tmpdir = tmpdir();
2710 if !got_symlink_permission(&tmpdir) { return };
2712 let f1 = tmpdir.join("f1");
2713 let f2 = tmpdir.join("f2");
2714 check!(check!(File::create(&f1)).write(b"foo"));
2715 check!(symlink_file(&f1, &f2));
2716 match fs::remove_dir_all(&f2) {
2717 Ok(..) => panic!("wanted a failure"),
2723 fn unicode_path_is_dir() {
2724 assert!(Path::new(".").is_dir());
2725 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2727 let tmpdir = tmpdir();
2729 let mut dirpath = tmpdir.path().to_path_buf();
2730 dirpath.push("test-가一ー你好");
2731 check!(fs::create_dir(&dirpath));
2732 assert!(dirpath.is_dir());
2734 let mut filepath = dirpath;
2735 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2736 check!(File::create(&filepath)); // ignore return; touch only
2737 assert!(!filepath.is_dir());
2738 assert!(filepath.exists());
2742 fn unicode_path_exists() {
2743 assert!(Path::new(".").exists());
2744 assert!(!Path::new("test/nonexistent-bogus-path").exists());
2746 let tmpdir = tmpdir();
2747 let unicode = tmpdir.path();
2748 let unicode = unicode.join("test-각丁ー再见");
2749 check!(fs::create_dir(&unicode));
2750 assert!(unicode.exists());
2751 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2755 fn copy_file_does_not_exist() {
2756 let from = Path::new("test/nonexistent-bogus-path");
2757 let to = Path::new("test/other-bogus-path");
2759 match fs::copy(&from, &to) {
2762 assert!(!from.exists());
2763 assert!(!to.exists());
2769 fn copy_src_does_not_exist() {
2770 let tmpdir = tmpdir();
2771 let from = Path::new("test/nonexistent-bogus-path");
2772 let to = tmpdir.join("out.txt");
2773 check!(check!(File::create(&to)).write(b"hello"));
2774 assert!(fs::copy(&from, &to).is_err());
2775 assert!(!from.exists());
2776 let mut v = Vec::new();
2777 check!(check!(File::open(&to)).read_to_end(&mut v));
2778 assert_eq!(v, b"hello");
2783 let tmpdir = tmpdir();
2784 let input = tmpdir.join("in.txt");
2785 let out = tmpdir.join("out.txt");
2787 check!(check!(File::create(&input)).write(b"hello"));
2788 check!(fs::copy(&input, &out));
2789 let mut v = Vec::new();
2790 check!(check!(File::open(&out)).read_to_end(&mut v));
2791 assert_eq!(v, b"hello");
2793 assert_eq!(check!(input.metadata()).permissions(),
2794 check!(out.metadata()).permissions());
2798 fn copy_file_dst_dir() {
2799 let tmpdir = tmpdir();
2800 let out = tmpdir.join("out");
2802 check!(File::create(&out));
2803 match fs::copy(&*out, tmpdir.path()) {
2804 Ok(..) => panic!(), Err(..) => {}
2809 fn copy_file_dst_exists() {
2810 let tmpdir = tmpdir();
2811 let input = tmpdir.join("in");
2812 let output = tmpdir.join("out");
2814 check!(check!(File::create(&input)).write("foo".as_bytes()));
2815 check!(check!(File::create(&output)).write("bar".as_bytes()));
2816 check!(fs::copy(&input, &output));
2818 let mut v = Vec::new();
2819 check!(check!(File::open(&output)).read_to_end(&mut v));
2820 assert_eq!(v, b"foo".to_vec());
2824 fn copy_file_src_dir() {
2825 let tmpdir = tmpdir();
2826 let out = tmpdir.join("out");
2828 match fs::copy(tmpdir.path(), &out) {
2829 Ok(..) => panic!(), Err(..) => {}
2831 assert!(!out.exists());
2835 fn copy_file_preserves_perm_bits() {
2836 let tmpdir = tmpdir();
2837 let input = tmpdir.join("in.txt");
2838 let out = tmpdir.join("out.txt");
2840 let attr = check!(check!(File::create(&input)).metadata());
2841 let mut p = attr.permissions();
2842 p.set_readonly(true);
2843 check!(fs::set_permissions(&input, p));
2844 check!(fs::copy(&input, &out));
2845 assert!(check!(out.metadata()).permissions().readonly());
2846 check!(fs::set_permissions(&input, attr.permissions()));
2847 check!(fs::set_permissions(&out, attr.permissions()));
2852 fn copy_file_preserves_streams() {
2854 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2855 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 0);
2856 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2857 let mut v = Vec::new();
2858 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2859 assert_eq!(v, b"carrot".to_vec());
2863 fn copy_file_returns_metadata_len() {
2865 let in_path = tmp.join("in.txt");
2866 let out_path = tmp.join("out.txt");
2867 check!(check!(File::create(&in_path)).write(b"lettuce"));
2869 check!(check!(File::create(tmp.join("in.txt:bunny"))).write(b"carrot"));
2870 let copied_len = check!(fs::copy(&in_path, &out_path));
2871 assert_eq!(check!(out_path.metadata()).len(), copied_len);
2875 fn copy_file_follows_dst_symlink() {
2877 if !got_symlink_permission(&tmp) { return };
2879 let in_path = tmp.join("in.txt");
2880 let out_path = tmp.join("out.txt");
2881 let out_path_symlink = tmp.join("out_symlink.txt");
2883 check!(fs::write(&in_path, "foo"));
2884 check!(fs::write(&out_path, "bar"));
2885 check!(symlink_file(&out_path, &out_path_symlink));
2887 check!(fs::copy(&in_path, &out_path_symlink));
2889 assert!(check!(out_path_symlink.symlink_metadata()).file_type().is_symlink());
2890 assert_eq!(check!(fs::read(&out_path_symlink)), b"foo".to_vec());
2891 assert_eq!(check!(fs::read(&out_path)), b"foo".to_vec());
2895 fn symlinks_work() {
2896 let tmpdir = tmpdir();
2897 if !got_symlink_permission(&tmpdir) { return };
2899 let input = tmpdir.join("in.txt");
2900 let out = tmpdir.join("out.txt");
2902 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2903 check!(symlink_file(&input, &out));
2904 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
2905 assert_eq!(check!(fs::metadata(&out)).len(),
2906 check!(fs::metadata(&input)).len());
2907 let mut v = Vec::new();
2908 check!(check!(File::open(&out)).read_to_end(&mut v));
2909 assert_eq!(v, b"foobar".to_vec());
2913 fn symlink_noexist() {
2914 // Symlinks can point to things that don't exist
2915 let tmpdir = tmpdir();
2916 if !got_symlink_permission(&tmpdir) { return };
2918 // Use a relative path for testing. Symlinks get normalized by Windows,
2919 // so we may not get the same path back for absolute paths
2920 check!(symlink_file(&"foo", &tmpdir.join("bar")));
2921 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(),
2928 // directory symlink
2929 assert_eq!(check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
2932 assert_eq!(check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
2933 r"C:\Users\Default");
2934 // junction with special permissions
2935 assert_eq!(check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
2938 let tmpdir = tmpdir();
2939 let link = tmpdir.join("link");
2940 if !got_symlink_permission(&tmpdir) { return };
2941 check!(symlink_file(&"foo", &link));
2942 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
2946 fn readlink_not_symlink() {
2947 let tmpdir = tmpdir();
2948 match fs::read_link(tmpdir.path()) {
2949 Ok(..) => panic!("wanted a failure"),
2956 let tmpdir = tmpdir();
2957 let input = tmpdir.join("in.txt");
2958 let out = tmpdir.join("out.txt");
2960 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2961 check!(fs::hard_link(&input, &out));
2962 assert_eq!(check!(fs::metadata(&out)).len(),
2963 check!(fs::metadata(&input)).len());
2964 assert_eq!(check!(fs::metadata(&out)).len(),
2965 check!(input.metadata()).len());
2966 let mut v = Vec::new();
2967 check!(check!(File::open(&out)).read_to_end(&mut v));
2968 assert_eq!(v, b"foobar".to_vec());
2970 // can't link to yourself
2971 match fs::hard_link(&input, &input) {
2972 Ok(..) => panic!("wanted a failure"),
2975 // can't link to something that doesn't exist
2976 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
2977 Ok(..) => panic!("wanted a failure"),
2984 let tmpdir = tmpdir();
2985 let file = tmpdir.join("in.txt");
2987 check!(File::create(&file));
2988 let attr = check!(fs::metadata(&file));
2989 assert!(!attr.permissions().readonly());
2990 let mut p = attr.permissions();
2991 p.set_readonly(true);
2992 check!(fs::set_permissions(&file, p.clone()));
2993 let attr = check!(fs::metadata(&file));
2994 assert!(attr.permissions().readonly());
2996 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
2997 Ok(..) => panic!("wanted an error"),
3001 p.set_readonly(false);
3002 check!(fs::set_permissions(&file, p));
3007 let tmpdir = tmpdir();
3008 let path = tmpdir.join("in.txt");
3010 let file = check!(File::create(&path));
3011 let attr = check!(fs::metadata(&path));
3012 assert!(!attr.permissions().readonly());
3013 let mut p = attr.permissions();
3014 p.set_readonly(true);
3015 check!(file.set_permissions(p.clone()));
3016 let attr = check!(fs::metadata(&path));
3017 assert!(attr.permissions().readonly());
3019 p.set_readonly(false);
3020 check!(file.set_permissions(p));
3024 fn sync_doesnt_kill_anything() {
3025 let tmpdir = tmpdir();
3026 let path = tmpdir.join("in.txt");
3028 let mut file = check!(File::create(&path));
3029 check!(file.sync_all());
3030 check!(file.sync_data());
3031 check!(file.write(b"foo"));
3032 check!(file.sync_all());
3033 check!(file.sync_data());
3037 fn truncate_works() {
3038 let tmpdir = tmpdir();
3039 let path = tmpdir.join("in.txt");
3041 let mut file = check!(File::create(&path));
3042 check!(file.write(b"foo"));
3043 check!(file.sync_all());
3045 // Do some simple things with truncation
3046 assert_eq!(check!(file.metadata()).len(), 3);
3047 check!(file.set_len(10));
3048 assert_eq!(check!(file.metadata()).len(), 10);
3049 check!(file.write(b"bar"));
3050 check!(file.sync_all());
3051 assert_eq!(check!(file.metadata()).len(), 10);
3053 let mut v = Vec::new();
3054 check!(check!(File::open(&path)).read_to_end(&mut v));
3055 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
3057 // Truncate to a smaller length, don't seek, and then write something.
3058 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
3059 // past the end of the file).
3060 check!(file.set_len(2));
3061 assert_eq!(check!(file.metadata()).len(), 2);
3062 check!(file.write(b"wut"));
3063 check!(file.sync_all());
3064 assert_eq!(check!(file.metadata()).len(), 9);
3065 let mut v = Vec::new();
3066 check!(check!(File::open(&path)).read_to_end(&mut v));
3067 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
3072 use crate::fs::OpenOptions as OO;
3073 fn c<T: Clone>(t: &T) -> T { t.clone() }
3075 let tmpdir = tmpdir();
3077 let mut r = OO::new(); r.read(true);
3078 let mut w = OO::new(); w.write(true);
3079 let mut rw = OO::new(); rw.read(true).write(true);
3080 let mut a = OO::new(); a.append(true);
3081 let mut ra = OO::new(); ra.read(true).append(true);
3084 let invalid_options = 87; // ERROR_INVALID_PARAMETER
3086 let invalid_options = "Invalid argument";
3088 // Test various combinations of creation modes and access modes.
3091 // creation mode | read | write | read-write | append | read-append |
3092 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
3093 // not set (open existing) | X | X | X | X | X |
3094 // create | | X | X | X | X |
3095 // truncate | | X | X | | |
3096 // create and truncate | | X | X | | |
3097 // create_new | | X | X | X | X |
3099 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
3102 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
3103 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
3104 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
3105 check!(c(&w).create(true).open(&tmpdir.join("a")));
3106 check!(c(&w).open(&tmpdir.join("a")));
3109 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
3110 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
3111 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
3112 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
3113 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
3116 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
3117 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
3118 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
3119 check!(c(&rw).create(true).open(&tmpdir.join("c")));
3120 check!(c(&rw).open(&tmpdir.join("c")));
3123 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
3124 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
3125 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
3126 check!(c(&a).create(true).open(&tmpdir.join("d")));
3127 check!(c(&a).open(&tmpdir.join("d")));
3130 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
3131 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
3132 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
3133 check!(c(&ra).create(true).open(&tmpdir.join("e")));
3134 check!(c(&ra).open(&tmpdir.join("e")));
3136 // Test opening a file without setting an access mode
3137 let mut blank = OO::new();
3138 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
3141 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
3143 // Test write fails for read-only
3144 check!(r.open(&tmpdir.join("h")));
3146 let mut f = check!(r.open(&tmpdir.join("h")));
3147 assert!(f.write("wut".as_bytes()).is_err());
3150 // Test write overwrites
3152 let mut f = check!(c(&w).open(&tmpdir.join("h")));
3153 check!(f.write("baz".as_bytes()));
3156 let mut f = check!(c(&r).open(&tmpdir.join("h")));
3157 let mut b = vec![0; 6];
3158 check!(f.read(&mut b));
3159 assert_eq!(b, "bazbar".as_bytes());
3162 // Test truncate works
3164 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
3165 check!(f.write("foo".as_bytes()));
3167 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3169 // Test append works
3170 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3172 let mut f = check!(c(&a).open(&tmpdir.join("h")));
3173 check!(f.write("bar".as_bytes()));
3175 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
3177 // Test .append(true) equals .write(true).append(true)
3179 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
3180 check!(f.write("baz".as_bytes()));
3182 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
3186 fn _assert_send_sync() {
3187 fn _assert_send_sync<T: Send + Sync>() {}
3188 _assert_send_sync::<OpenOptions>();
3193 let mut bytes = [0; 1024];
3194 StdRng::from_entropy().fill_bytes(&mut bytes);
3196 let tmpdir = tmpdir();
3198 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
3199 let mut v = Vec::new();
3200 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
3201 assert!(v == &bytes[..]);
3205 fn write_then_read() {
3206 let mut bytes = [0; 1024];
3207 StdRng::from_entropy().fill_bytes(&mut bytes);
3209 let tmpdir = tmpdir();
3211 check!(fs::write(&tmpdir.join("test"), &bytes[..]));
3212 let v = check!(fs::read(&tmpdir.join("test")));
3213 assert!(v == &bytes[..]);
3215 check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF]));
3216 error_contains!(fs::read_to_string(&tmpdir.join("not-utf8")),
3217 "stream did not contain valid UTF-8");
3220 check!(fs::write(&tmpdir.join("utf8"), s.as_bytes()));
3221 let string = check!(fs::read_to_string(&tmpdir.join("utf8")));
3222 assert_eq!(string, s);
3226 fn file_try_clone() {
3227 let tmpdir = tmpdir();
3229 let mut f1 = check!(OpenOptions::new()
3233 .open(&tmpdir.join("test")));
3234 let mut f2 = check!(f1.try_clone());
3236 check!(f1.write_all(b"hello world"));
3237 check!(f1.seek(SeekFrom::Start(2)));
3239 let mut buf = vec![];
3240 check!(f2.read_to_end(&mut buf));
3241 assert_eq!(buf, b"llo world");
3244 check!(f1.write_all(b"!"));
3248 #[cfg(not(windows))]
3249 fn unlink_readonly() {
3250 let tmpdir = tmpdir();
3251 let path = tmpdir.join("file");
3252 check!(File::create(&path));
3253 let mut perm = check!(fs::metadata(&path)).permissions();
3254 perm.set_readonly(true);
3255 check!(fs::set_permissions(&path, perm));
3256 check!(fs::remove_file(&path));
3260 fn mkdir_trailing_slash() {
3261 let tmpdir = tmpdir();
3262 let path = tmpdir.join("file");
3263 check!(fs::create_dir_all(&path.join("a/")));
3267 fn canonicalize_works_simple() {
3268 let tmpdir = tmpdir();
3269 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3270 let file = tmpdir.join("test");
3271 File::create(&file).unwrap();
3272 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3276 fn realpath_works() {
3277 let tmpdir = tmpdir();
3278 if !got_symlink_permission(&tmpdir) { return };
3280 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3281 let file = tmpdir.join("test");
3282 let dir = tmpdir.join("test2");
3283 let link = dir.join("link");
3284 let linkdir = tmpdir.join("test3");
3286 File::create(&file).unwrap();
3287 fs::create_dir(&dir).unwrap();
3288 symlink_file(&file, &link).unwrap();
3289 symlink_dir(&dir, &linkdir).unwrap();
3291 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
3293 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
3294 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3295 assert_eq!(fs::canonicalize(&link).unwrap(), file);
3296 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
3297 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
3301 fn realpath_works_tricky() {
3302 let tmpdir = tmpdir();
3303 if !got_symlink_permission(&tmpdir) { return };
3305 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3306 let a = tmpdir.join("a");
3307 let b = a.join("b");
3308 let c = b.join("c");
3309 let d = a.join("d");
3310 let e = d.join("e");
3311 let f = a.join("f");
3313 fs::create_dir_all(&b).unwrap();
3314 fs::create_dir_all(&d).unwrap();
3315 File::create(&f).unwrap();
3316 if cfg!(not(windows)) {
3317 symlink_dir("../d/e", &c).unwrap();
3318 symlink_file("../f", &e).unwrap();
3321 symlink_dir(r"..\d\e", &c).unwrap();
3322 symlink_file(r"..\f", &e).unwrap();
3325 assert_eq!(fs::canonicalize(&c).unwrap(), f);
3326 assert_eq!(fs::canonicalize(&e).unwrap(), f);
3330 fn dir_entry_methods() {
3331 let tmpdir = tmpdir();
3333 fs::create_dir_all(&tmpdir.join("a")).unwrap();
3334 File::create(&tmpdir.join("b")).unwrap();
3336 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
3337 let fname = file.file_name();
3338 match fname.to_str() {
3340 assert!(file.file_type().unwrap().is_dir());
3341 assert!(file.metadata().unwrap().is_dir());
3344 assert!(file.file_type().unwrap().is_file());
3345 assert!(file.metadata().unwrap().is_file());
3347 f => panic!("unknown file name: {:?}", f),
3353 fn dir_entry_debug() {
3354 let tmpdir = tmpdir();
3355 File::create(&tmpdir.join("b")).unwrap();
3356 let mut read_dir = tmpdir.path().read_dir().unwrap();
3357 let dir_entry = read_dir.next().unwrap().unwrap();
3358 let actual = format!("{:?}", dir_entry);
3359 let expected = format!("DirEntry({:?})", dir_entry.0.path());
3360 assert_eq!(actual, expected);
3364 fn read_dir_not_found() {
3365 let res = fs::read_dir("/path/that/does/not/exist");
3366 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
3370 fn create_dir_all_with_junctions() {
3371 let tmpdir = tmpdir();
3372 let target = tmpdir.join("target");
3374 let junction = tmpdir.join("junction");
3375 let b = junction.join("a/b");
3377 let link = tmpdir.join("link");
3378 let d = link.join("c/d");
3380 fs::create_dir(&target).unwrap();
3382 check!(symlink_junction(&target, &junction));
3383 check!(fs::create_dir_all(&b));
3384 // the junction itself is not a directory, but `is_dir()` on a Path
3386 assert!(junction.is_dir());
3387 assert!(b.exists());
3389 if !got_symlink_permission(&tmpdir) { return };
3390 check!(symlink_dir(&target, &link));
3391 check!(fs::create_dir_all(&d));
3392 assert!(link.is_dir());
3393 assert!(d.exists());
3397 fn metadata_access_times() {
3398 let tmpdir = tmpdir();
3400 let b = tmpdir.join("b");
3401 File::create(&b).unwrap();
3403 let a = check!(fs::metadata(&tmpdir.path()));
3404 let b = check!(fs::metadata(&b));
3406 assert_eq!(check!(a.accessed()), check!(a.accessed()));
3407 assert_eq!(check!(a.modified()), check!(a.modified()));
3408 assert_eq!(check!(b.accessed()), check!(b.modified()));
3410 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3411 check!(a.created());
3412 check!(b.created());