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
117 /// The order in which this iterator returns entries is platform and filesystem
122 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
123 /// IO error during iteration.
125 /// [`read_dir`]: fn.read_dir.html
126 /// [`DirEntry`]: struct.DirEntry.html
127 /// [`io::Result`]: ../io/type.Result.html
128 /// [`Err`]: ../result/enum.Result.html#variant.Err
129 #[stable(feature = "rust1", since = "1.0.0")]
131 pub struct ReadDir(fs_imp::ReadDir);
133 /// Entries returned by the [`ReadDir`] iterator.
135 /// [`ReadDir`]: struct.ReadDir.html
137 /// An instance of `DirEntry` represents an entry inside of a directory on the
138 /// filesystem. Each entry can be inspected via methods to learn about the full
139 /// path or possibly other metadata through per-platform extension traits.
140 #[stable(feature = "rust1", since = "1.0.0")]
141 pub struct DirEntry(fs_imp::DirEntry);
143 /// Options and flags which can be used to configure how a file is opened.
145 /// This builder exposes the ability to configure how a [`File`] is opened and
146 /// what operations are permitted on the open file. The [`File::open`] and
147 /// [`File::create`] methods are aliases for commonly used options using this
150 /// [`File`]: struct.File.html
151 /// [`File::open`]: struct.File.html#method.open
152 /// [`File::create`]: struct.File.html#method.create
154 /// Generally speaking, when using `OpenOptions`, you'll first call [`new`],
155 /// then chain calls to methods to set each option, then call [`open`],
156 /// passing the path of the file you're trying to open. This will give you a
157 /// [`io::Result`][result] with a [`File`][file] inside that you can further
160 /// [`new`]: struct.OpenOptions.html#method.new
161 /// [`open`]: struct.OpenOptions.html#method.open
162 /// [result]: ../io/type.Result.html
163 /// [file]: struct.File.html
167 /// Opening a file to read:
170 /// use std::fs::OpenOptions;
172 /// let file = OpenOptions::new().read(true).open("foo.txt");
175 /// Opening a file for both reading and writing, as well as creating it if it
179 /// use std::fs::OpenOptions;
181 /// let file = OpenOptions::new()
185 /// .open("foo.txt");
187 #[derive(Clone, Debug)]
188 #[stable(feature = "rust1", since = "1.0.0")]
189 pub struct OpenOptions(fs_imp::OpenOptions);
191 /// Representation of the various permissions on a file.
193 /// This module only currently provides one bit of information, [`readonly`],
194 /// which is exposed on all currently supported platforms. Unix-specific
195 /// functionality, such as mode bits, is available through the
196 /// [`PermissionsExt`] trait.
198 /// [`readonly`]: struct.Permissions.html#method.readonly
199 /// [`PermissionsExt`]: ../os/unix/fs/trait.PermissionsExt.html
200 #[derive(Clone, PartialEq, Eq, Debug)]
201 #[stable(feature = "rust1", since = "1.0.0")]
202 pub struct Permissions(fs_imp::FilePermissions);
204 /// A structure representing a type of file with accessors for each file type.
205 /// It is returned by [`Metadata::file_type`] method.
207 /// [`Metadata::file_type`]: struct.Metadata.html#method.file_type
208 #[stable(feature = "file_type", since = "1.1.0")]
209 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
210 pub struct FileType(fs_imp::FileType);
212 /// A builder used to create directories in various manners.
214 /// This builder also supports platform-specific options.
215 #[stable(feature = "dir_builder", since = "1.6.0")]
217 pub struct DirBuilder {
218 inner: fs_imp::DirBuilder,
222 /// Indicates how large a buffer to pre-allocate before reading the entire file.
223 fn initial_buffer_size(file: &File) -> usize {
224 // Allocate one extra byte so the buffer doesn't need to grow before the
225 // final `read` call at the end of the file. Don't worry about `usize`
226 // overflow because reading will fail regardless in that case.
227 file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
230 /// Read the entire contents of a file into a bytes vector.
232 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
233 /// with fewer imports and without an intermediate variable. It pre-allocates a
234 /// buffer based on the file size when available, so it is generally faster than
235 /// reading into a vector created with `Vec::new()`.
237 /// [`File::open`]: struct.File.html#method.open
238 /// [`read_to_end`]: ../io/trait.Read.html#method.read_to_end
242 /// This function will return an error if `path` does not already exist.
243 /// Other errors may also be returned according to [`OpenOptions::open`].
245 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
247 /// It will also return an error if it encounters while reading an error
248 /// of a kind other than [`ErrorKind::Interrupted`].
250 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
256 /// use std::net::SocketAddr;
258 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
259 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
263 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
264 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
265 fn inner(path: &Path) -> io::Result<Vec<u8>> {
266 let mut file = File::open(path)?;
267 let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
268 file.read_to_end(&mut bytes)?;
274 /// Read the entire contents of a file into a string.
276 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
277 /// with fewer imports and without an intermediate variable. It pre-allocates a
278 /// buffer based on the file size when available, so it is generally faster than
279 /// reading into a string created with `String::new()`.
281 /// [`File::open`]: struct.File.html#method.open
282 /// [`read_to_string`]: ../io/trait.Read.html#method.read_to_string
286 /// This function will return an error if `path` does not already exist.
287 /// Other errors may also be returned according to [`OpenOptions::open`].
289 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
291 /// It will also return an error if it encounters while reading an error
292 /// of a kind other than [`ErrorKind::Interrupted`],
293 /// or if the contents of the file are not valid UTF-8.
295 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
301 /// use std::net::SocketAddr;
303 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
304 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
308 #[stable(feature = "fs_read_write", since = "1.26.0")]
309 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
310 fn inner(path: &Path) -> io::Result<String> {
311 let mut file = File::open(path)?;
312 let mut string = String::with_capacity(initial_buffer_size(&file));
313 file.read_to_string(&mut string)?;
319 /// Write a slice as the entire contents of a file.
321 /// This function will create a file if it does not exist,
322 /// and will entirely replace its contents if it does.
324 /// This is a convenience function for using [`File::create`] and [`write_all`]
325 /// with fewer imports.
327 /// [`File::create`]: struct.File.html#method.create
328 /// [`write_all`]: ../io/trait.Write.html#method.write_all
335 /// fn main() -> std::io::Result<()> {
336 /// fs::write("foo.txt", b"Lorem ipsum")?;
337 /// fs::write("bar.txt", "dolor sit")?;
341 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
342 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
343 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
344 File::create(path)?.write_all(contents)
346 inner(path.as_ref(), contents.as_ref())
350 /// Attempts to open a file in read-only mode.
352 /// See the [`OpenOptions::open`] method for more details.
356 /// This function will return an error if `path` does not already exist.
357 /// Other errors may also be returned according to [`OpenOptions::open`].
359 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
364 /// use std::fs::File;
366 /// fn main() -> std::io::Result<()> {
367 /// let mut f = File::open("foo.txt")?;
371 #[stable(feature = "rust1", since = "1.0.0")]
372 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
373 OpenOptions::new().read(true).open(path.as_ref())
376 /// Opens a file in write-only mode.
378 /// This function will create a file if it does not exist,
379 /// and will truncate it if it does.
381 /// See the [`OpenOptions::open`] function for more details.
383 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
388 /// use std::fs::File;
390 /// fn main() -> std::io::Result<()> {
391 /// let mut f = File::create("foo.txt")?;
395 #[stable(feature = "rust1", since = "1.0.0")]
396 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
397 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
400 /// Attempts to sync all OS-internal metadata to disk.
402 /// This function will attempt to ensure that all in-memory data reaches the
403 /// filesystem before returning.
405 /// This can be used to handle errors that would otherwise only be caught
406 /// when the `File` is closed. Dropping a file will ignore errors in
407 /// synchronizing this in-memory data.
412 /// use std::fs::File;
413 /// use std::io::prelude::*;
415 /// fn main() -> std::io::Result<()> {
416 /// let mut f = File::create("foo.txt")?;
417 /// f.write_all(b"Hello, world!")?;
423 #[stable(feature = "rust1", since = "1.0.0")]
424 pub fn sync_all(&self) -> io::Result<()> {
428 /// This function is similar to [`sync_all`], except that it may not
429 /// synchronize file metadata to the filesystem.
431 /// This is intended for use cases that must synchronize content, but don't
432 /// need the metadata on disk. The goal of this method is to reduce disk
435 /// Note that some platforms may simply implement this in terms of
438 /// [`sync_all`]: struct.File.html#method.sync_all
443 /// use std::fs::File;
444 /// use std::io::prelude::*;
446 /// fn main() -> std::io::Result<()> {
447 /// let mut f = File::create("foo.txt")?;
448 /// f.write_all(b"Hello, world!")?;
454 #[stable(feature = "rust1", since = "1.0.0")]
455 pub fn sync_data(&self) -> io::Result<()> {
456 self.inner.datasync()
459 /// Truncates or extends the underlying file, updating the size of
460 /// this file to become `size`.
462 /// If the `size` is less than the current file's size, then the file will
463 /// be shrunk. If it is greater than the current file's size, then the file
464 /// will be extended to `size` and have all of the intermediate data filled
467 /// The file's cursor isn't changed. In particular, if the cursor was at the
468 /// end and the file is shrunk using this operation, the cursor will now be
473 /// This function will return an error if the file is not opened for writing.
474 /// Also, std::io::ErrorKind::InvalidInput will be returned if the desired
475 /// length would cause an overflow due to the implementation specifics.
480 /// use std::fs::File;
482 /// fn main() -> std::io::Result<()> {
483 /// let mut f = File::create("foo.txt")?;
489 /// Note that this method alters the content of the underlying file, even
490 /// though it takes `&self` rather than `&mut self`.
491 #[stable(feature = "rust1", since = "1.0.0")]
492 pub fn set_len(&self, size: u64) -> io::Result<()> {
493 self.inner.truncate(size)
496 /// Queries metadata about the underlying file.
501 /// use std::fs::File;
503 /// fn main() -> std::io::Result<()> {
504 /// let mut f = File::open("foo.txt")?;
505 /// let metadata = f.metadata()?;
509 #[stable(feature = "rust1", since = "1.0.0")]
510 pub fn metadata(&self) -> io::Result<Metadata> {
511 self.inner.file_attr().map(Metadata)
514 /// Creates a new `File` instance that shares the same underlying file handle
515 /// as the existing `File` instance. Reads, writes, and seeks will affect
516 /// both `File` instances simultaneously.
520 /// Creates two handles for a file named `foo.txt`:
523 /// use std::fs::File;
525 /// fn main() -> std::io::Result<()> {
526 /// let mut file = File::open("foo.txt")?;
527 /// let file_copy = file.try_clone()?;
532 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
533 /// two handles, seek one of them, and read the remaining bytes from the
537 /// use std::fs::File;
538 /// use std::io::SeekFrom;
539 /// use std::io::prelude::*;
541 /// fn main() -> std::io::Result<()> {
542 /// let mut file = File::open("foo.txt")?;
543 /// let mut file_copy = file.try_clone()?;
545 /// file.seek(SeekFrom::Start(3))?;
547 /// let mut contents = vec![];
548 /// file_copy.read_to_end(&mut contents)?;
549 /// assert_eq!(contents, b"def\n");
553 #[stable(feature = "file_try_clone", since = "1.9.0")]
554 pub fn try_clone(&self) -> io::Result<File> {
556 inner: self.inner.duplicate()?
560 /// Changes the permissions on the underlying file.
562 /// # Platform-specific behavior
564 /// This function currently corresponds to the `fchmod` function on Unix and
565 /// the `SetFileInformationByHandle` function on Windows. Note that, this
566 /// [may change in the future][changes].
568 /// [changes]: ../io/index.html#platform-specific-behavior
572 /// This function will return an error if the user lacks permission change
573 /// attributes on the underlying file. It may also return an error in other
574 /// os-specific unspecified cases.
579 /// fn main() -> std::io::Result<()> {
580 /// use std::fs::File;
582 /// let file = File::open("foo.txt")?;
583 /// let mut perms = file.metadata()?.permissions();
584 /// perms.set_readonly(true);
585 /// file.set_permissions(perms)?;
590 /// Note that this method alters the permissions of the underlying file,
591 /// even though it takes `&self` rather than `&mut self`.
592 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
593 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
594 self.inner.set_permissions(perm.0)
598 impl AsInner<fs_imp::File> for File {
599 fn as_inner(&self) -> &fs_imp::File { &self.inner }
601 impl FromInner<fs_imp::File> for File {
602 fn from_inner(f: fs_imp::File) -> File {
606 impl IntoInner<fs_imp::File> for File {
607 fn into_inner(self) -> fs_imp::File {
612 #[stable(feature = "rust1", since = "1.0.0")]
613 impl fmt::Debug for File {
614 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
619 #[stable(feature = "rust1", since = "1.0.0")]
621 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
625 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
626 self.inner.read_vectored(bufs)
630 unsafe fn initializer(&self) -> Initializer {
634 #[stable(feature = "rust1", since = "1.0.0")]
635 impl Write for File {
636 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
637 self.inner.write(buf)
640 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
641 self.inner.write_vectored(bufs)
644 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
646 #[stable(feature = "rust1", since = "1.0.0")]
648 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
652 #[stable(feature = "rust1", since = "1.0.0")]
653 impl Read for &File {
654 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
658 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
659 self.inner.read_vectored(bufs)
663 unsafe fn initializer(&self) -> Initializer {
667 #[stable(feature = "rust1", since = "1.0.0")]
668 impl Write for &File {
669 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
670 self.inner.write(buf)
673 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
674 self.inner.write_vectored(bufs)
677 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
679 #[stable(feature = "rust1", since = "1.0.0")]
680 impl Seek for &File {
681 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
687 /// Creates a blank new set of options ready for configuration.
689 /// All options are initially set to `false`.
694 /// use std::fs::OpenOptions;
696 /// let mut options = OpenOptions::new();
697 /// let file = options.read(true).open("foo.txt");
699 #[stable(feature = "rust1", since = "1.0.0")]
700 pub fn new() -> OpenOptions {
701 OpenOptions(fs_imp::OpenOptions::new())
704 /// Sets the option for read access.
706 /// This option, when true, will indicate that the file should be
707 /// `read`-able if opened.
712 /// use std::fs::OpenOptions;
714 /// let file = OpenOptions::new().read(true).open("foo.txt");
716 #[stable(feature = "rust1", since = "1.0.0")]
717 pub fn read(&mut self, read: bool) -> &mut OpenOptions {
718 self.0.read(read); self
721 /// Sets the option for write access.
723 /// This option, when true, will indicate that the file should be
724 /// `write`-able if opened.
726 /// If the file already exists, any write calls on it will overwrite its
727 /// contents, without truncating it.
732 /// use std::fs::OpenOptions;
734 /// let file = OpenOptions::new().write(true).open("foo.txt");
736 #[stable(feature = "rust1", since = "1.0.0")]
737 pub fn write(&mut self, write: bool) -> &mut OpenOptions {
738 self.0.write(write); self
741 /// Sets the option for the append mode.
743 /// This option, when true, means that writes will append to a file instead
744 /// of overwriting previous contents.
745 /// Note that setting `.write(true).append(true)` has the same effect as
746 /// setting only `.append(true)`.
748 /// For most filesystems, the operating system guarantees that all writes are
749 /// atomic: no writes get mangled because another process writes at the same
752 /// One maybe obvious note when using append-mode: make sure that all data
753 /// that belongs together is written to the file in one operation. This
754 /// can be done by concatenating strings before passing them to [`write()`],
755 /// or using a buffered writer (with a buffer of adequate size),
756 /// and calling [`flush()`] when the message is complete.
758 /// If a file is opened with both read and append access, beware that after
759 /// opening, and after every write, the position for reading may be set at the
760 /// end of the file. So, before writing, save the current position (using
761 /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`), and restore it before the next read.
765 /// This function doesn't create the file if it doesn't exist. Use the [`create`]
768 /// [`write()`]: ../../std/fs/struct.File.html#method.write
769 /// [`flush()`]: ../../std/fs/struct.File.html#method.flush
770 /// [`seek`]: ../../std/fs/struct.File.html#method.seek
771 /// [`SeekFrom`]: ../../std/io/enum.SeekFrom.html
772 /// [`Current`]: ../../std/io/enum.SeekFrom.html#variant.Current
773 /// [`create`]: #method.create
778 /// use std::fs::OpenOptions;
780 /// let file = OpenOptions::new().append(true).open("foo.txt");
782 #[stable(feature = "rust1", since = "1.0.0")]
783 pub fn append(&mut self, append: bool) -> &mut OpenOptions {
784 self.0.append(append); self
787 /// Sets the option for truncating a previous file.
789 /// If a file is successfully opened with this option set it will truncate
790 /// the file to 0 length if it already exists.
792 /// The file must be opened with write access for truncate to work.
797 /// use std::fs::OpenOptions;
799 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
801 #[stable(feature = "rust1", since = "1.0.0")]
802 pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
803 self.0.truncate(truncate); self
806 /// Sets the option for creating a new file.
808 /// This option indicates whether a new file will be created if the file
809 /// does not yet already exist.
811 /// In order for the file to be created, [`write`] or [`append`] access must
814 /// [`write`]: #method.write
815 /// [`append`]: #method.append
820 /// use std::fs::OpenOptions;
822 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
824 #[stable(feature = "rust1", since = "1.0.0")]
825 pub fn create(&mut self, create: bool) -> &mut OpenOptions {
826 self.0.create(create); self
829 /// Sets the option to always create a new file.
831 /// This option indicates whether a new file will be created.
832 /// No file is allowed to exist at the target location, also no (dangling)
835 /// This option is useful because it is atomic. Otherwise between checking
836 /// whether a file exists and creating a new one, the file may have been
837 /// created by another process (a TOCTOU race condition / attack).
839 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
842 /// The file must be opened with write or append access in order to create
845 /// [`.create()`]: #method.create
846 /// [`.truncate()`]: #method.truncate
851 /// use std::fs::OpenOptions;
853 /// let file = OpenOptions::new().write(true)
854 /// .create_new(true)
855 /// .open("foo.txt");
857 #[stable(feature = "expand_open_options2", since = "1.9.0")]
858 pub fn create_new(&mut self, create_new: bool) -> &mut OpenOptions {
859 self.0.create_new(create_new); self
862 /// Opens a file at `path` with the options specified by `self`.
866 /// This function will return an error under a number of different
867 /// circumstances. Some of these error conditions are listed here, together
868 /// with their [`ErrorKind`]. The mapping to [`ErrorKind`]s is not part of
869 /// the compatibility contract of the function, especially the `Other` kind
870 /// might change to more specific kinds in the future.
872 /// * [`NotFound`]: The specified file does not exist and neither `create`
873 /// or `create_new` is set.
874 /// * [`NotFound`]: One of the directory components of the file path does
876 /// * [`PermissionDenied`]: The user lacks permission to get the specified
877 /// access rights for the file.
878 /// * [`PermissionDenied`]: The user lacks permission to open one of the
879 /// directory components of the specified path.
880 /// * [`AlreadyExists`]: `create_new` was specified and the file already
882 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
883 /// without write access, no access mode set, etc.).
884 /// * [`Other`]: One of the directory components of the specified file path
885 /// was not, in fact, a directory.
886 /// * [`Other`]: Filesystem-level errors: full disk, write permission
887 /// requested on a read-only file system, exceeded disk quota, too many
888 /// open files, too long filename, too many symbolic links in the
889 /// specified path (Unix-like systems only), etc.
894 /// use std::fs::OpenOptions;
896 /// let file = OpenOptions::new().open("foo.txt");
899 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
900 /// [`AlreadyExists`]: ../io/enum.ErrorKind.html#variant.AlreadyExists
901 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
902 /// [`NotFound`]: ../io/enum.ErrorKind.html#variant.NotFound
903 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
904 /// [`PermissionDenied`]: ../io/enum.ErrorKind.html#variant.PermissionDenied
905 #[stable(feature = "rust1", since = "1.0.0")]
906 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
907 self._open(path.as_ref())
910 fn _open(&self, path: &Path) -> io::Result<File> {
911 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
915 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
916 fn as_inner(&self) -> &fs_imp::OpenOptions { &self.0 }
919 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
920 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
924 /// Returns the file type for this metadata.
929 /// fn main() -> std::io::Result<()> {
932 /// let metadata = fs::metadata("foo.txt")?;
934 /// println!("{:?}", metadata.file_type());
938 #[stable(feature = "file_type", since = "1.1.0")]
939 pub fn file_type(&self) -> FileType {
940 FileType(self.0.file_type())
943 /// Returns `true` if this metadata is for a directory. The
944 /// result is mutually exclusive to the result of
945 /// [`is_file`], and will be false for symlink metadata
946 /// obtained from [`symlink_metadata`].
948 /// [`is_file`]: struct.Metadata.html#method.is_file
949 /// [`symlink_metadata`]: fn.symlink_metadata.html
954 /// fn main() -> std::io::Result<()> {
957 /// let metadata = fs::metadata("foo.txt")?;
959 /// assert!(!metadata.is_dir());
963 #[stable(feature = "rust1", since = "1.0.0")]
964 pub fn is_dir(&self) -> bool { self.file_type().is_dir() }
966 /// Returns `true` if this metadata is for a regular file. The
967 /// result is mutually exclusive to the result of
968 /// [`is_dir`], and will be false for symlink metadata
969 /// obtained from [`symlink_metadata`].
971 /// [`is_dir`]: struct.Metadata.html#method.is_dir
972 /// [`symlink_metadata`]: fn.symlink_metadata.html
979 /// fn main() -> std::io::Result<()> {
980 /// let metadata = fs::metadata("foo.txt")?;
982 /// assert!(metadata.is_file());
986 #[stable(feature = "rust1", since = "1.0.0")]
987 pub fn is_file(&self) -> bool { self.file_type().is_file() }
989 /// Returns the size of the file, in bytes, this metadata is for.
996 /// fn main() -> std::io::Result<()> {
997 /// let metadata = fs::metadata("foo.txt")?;
999 /// assert_eq!(0, metadata.len());
1003 #[stable(feature = "rust1", since = "1.0.0")]
1004 pub fn len(&self) -> u64 { self.0.size() }
1006 /// Returns the permissions of the file this metadata is for.
1013 /// fn main() -> std::io::Result<()> {
1014 /// let metadata = fs::metadata("foo.txt")?;
1016 /// assert!(!metadata.permissions().readonly());
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 pub fn permissions(&self) -> Permissions {
1022 Permissions(self.0.perm())
1025 /// Returns the last modification time listed in this metadata.
1027 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1028 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1032 /// This field may not be available on all platforms, and will return an
1033 /// `Err` on platforms where it is not available.
1040 /// fn main() -> std::io::Result<()> {
1041 /// let metadata = fs::metadata("foo.txt")?;
1043 /// if let Ok(time) = metadata.modified() {
1044 /// println!("{:?}", time);
1046 /// println!("Not supported on this platform");
1051 #[stable(feature = "fs_time", since = "1.10.0")]
1052 pub fn modified(&self) -> io::Result<SystemTime> {
1053 self.0.modified().map(FromInner::from_inner)
1056 /// Returns the last access time of this metadata.
1058 /// The returned value corresponds to the `atime` field of `stat` on Unix
1059 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1061 /// Note that not all platforms will keep this field update in a file's
1062 /// metadata, for example Windows has an option to disable updating this
1063 /// time when files are accessed and Linux similarly has `noatime`.
1067 /// This field may not be available on all platforms, and will return an
1068 /// `Err` on platforms where it is not available.
1075 /// fn main() -> std::io::Result<()> {
1076 /// let metadata = fs::metadata("foo.txt")?;
1078 /// if let Ok(time) = metadata.accessed() {
1079 /// println!("{:?}", time);
1081 /// println!("Not supported on this platform");
1086 #[stable(feature = "fs_time", since = "1.10.0")]
1087 pub fn accessed(&self) -> io::Result<SystemTime> {
1088 self.0.accessed().map(FromInner::from_inner)
1091 /// Returns the creation time listed in this metadata.
1093 /// The returned value corresponds to the `btime` field of `statx` on
1094 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1095 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1099 /// This field may not be available on all platforms, and will return an
1100 /// `Err` on platforms or filesystems where it is not available.
1107 /// fn main() -> std::io::Result<()> {
1108 /// let metadata = fs::metadata("foo.txt")?;
1110 /// if let Ok(time) = metadata.created() {
1111 /// println!("{:?}", time);
1113 /// println!("Not supported on this platform or filesystem");
1118 #[stable(feature = "fs_time", since = "1.10.0")]
1119 pub fn created(&self) -> io::Result<SystemTime> {
1120 self.0.created().map(FromInner::from_inner)
1124 #[stable(feature = "std_debug", since = "1.16.0")]
1125 impl fmt::Debug for Metadata {
1126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1127 f.debug_struct("Metadata")
1128 .field("file_type", &self.file_type())
1129 .field("is_dir", &self.is_dir())
1130 .field("is_file", &self.is_file())
1131 .field("permissions", &self.permissions())
1132 .field("modified", &self.modified())
1133 .field("accessed", &self.accessed())
1134 .field("created", &self.created())
1139 impl AsInner<fs_imp::FileAttr> for Metadata {
1140 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
1143 impl FromInner<fs_imp::FileAttr> for Metadata {
1144 fn from_inner(attr: fs_imp::FileAttr) -> Metadata { Metadata(attr) }
1148 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1153 /// use std::fs::File;
1155 /// fn main() -> std::io::Result<()> {
1156 /// let mut f = File::create("foo.txt")?;
1157 /// let metadata = f.metadata()?;
1159 /// assert_eq!(false, metadata.permissions().readonly());
1163 #[stable(feature = "rust1", since = "1.0.0")]
1164 pub fn readonly(&self) -> bool { self.0.readonly() }
1166 /// Modifies the readonly flag for this set of permissions. If the
1167 /// `readonly` argument is `true`, using the resulting `Permission` will
1168 /// update file permissions to forbid writing. Conversely, if it's `false`,
1169 /// using the resulting `Permission` will update file permissions to allow
1172 /// This operation does **not** modify the filesystem. To modify the
1173 /// filesystem use the [`fs::set_permissions`] function.
1175 /// [`fs::set_permissions`]: fn.set_permissions.html
1180 /// use std::fs::File;
1182 /// fn main() -> std::io::Result<()> {
1183 /// let f = File::create("foo.txt")?;
1184 /// let metadata = f.metadata()?;
1185 /// let mut permissions = metadata.permissions();
1187 /// permissions.set_readonly(true);
1189 /// // filesystem doesn't change
1190 /// assert_eq!(false, metadata.permissions().readonly());
1192 /// // just this particular `permissions`.
1193 /// assert_eq!(true, permissions.readonly());
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 pub fn set_readonly(&mut self, readonly: bool) {
1199 self.0.set_readonly(readonly)
1204 /// Tests whether this file type represents a directory. The
1205 /// result is mutually exclusive to the results of
1206 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1209 /// [`is_file`]: struct.FileType.html#method.is_file
1210 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1215 /// fn main() -> std::io::Result<()> {
1218 /// let metadata = fs::metadata("foo.txt")?;
1219 /// let file_type = metadata.file_type();
1221 /// assert_eq!(file_type.is_dir(), false);
1225 #[stable(feature = "file_type", since = "1.1.0")]
1226 pub fn is_dir(&self) -> bool { self.0.is_dir() }
1228 /// Tests whether this file type represents a regular file.
1229 /// The result is mutually exclusive to the results of
1230 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1233 /// [`is_dir`]: struct.FileType.html#method.is_dir
1234 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1239 /// fn main() -> std::io::Result<()> {
1242 /// let metadata = fs::metadata("foo.txt")?;
1243 /// let file_type = metadata.file_type();
1245 /// assert_eq!(file_type.is_file(), true);
1249 #[stable(feature = "file_type", since = "1.1.0")]
1250 pub fn is_file(&self) -> bool { self.0.is_file() }
1252 /// Tests whether this file type represents a symbolic link.
1253 /// The result is mutually exclusive to the results of
1254 /// [`is_dir`] and [`is_file`]; only zero or one of these
1257 /// The underlying [`Metadata`] struct needs to be retrieved
1258 /// with the [`fs::symlink_metadata`] function and not the
1259 /// [`fs::metadata`] function. The [`fs::metadata`] function
1260 /// follows symbolic links, so [`is_symlink`] would always
1261 /// return `false` for the target file.
1263 /// [`Metadata`]: struct.Metadata.html
1264 /// [`fs::metadata`]: fn.metadata.html
1265 /// [`fs::symlink_metadata`]: fn.symlink_metadata.html
1266 /// [`is_dir`]: struct.FileType.html#method.is_dir
1267 /// [`is_file`]: struct.FileType.html#method.is_file
1268 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1275 /// fn main() -> std::io::Result<()> {
1276 /// let metadata = fs::symlink_metadata("foo.txt")?;
1277 /// let file_type = metadata.file_type();
1279 /// assert_eq!(file_type.is_symlink(), false);
1283 #[stable(feature = "file_type", since = "1.1.0")]
1284 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
1287 impl AsInner<fs_imp::FileType> for FileType {
1288 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
1291 impl FromInner<fs_imp::FilePermissions> for Permissions {
1292 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1297 impl AsInner<fs_imp::FilePermissions> for Permissions {
1298 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 impl Iterator for ReadDir {
1303 type Item = io::Result<DirEntry>;
1305 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1306 self.0.next().map(|entry| entry.map(DirEntry))
1311 /// Returns the full path to the file that this entry represents.
1313 /// The full path is created by joining the original path to `read_dir`
1314 /// with the filename of this entry.
1321 /// fn main() -> std::io::Result<()> {
1322 /// for entry in fs::read_dir(".")? {
1323 /// let dir = entry?;
1324 /// println!("{:?}", dir.path());
1330 /// This prints output like:
1333 /// "./whatever.txt"
1335 /// "./hello_world.rs"
1338 /// The exact text, of course, depends on what files you have in `.`.
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 pub fn path(&self) -> PathBuf { self.0.path() }
1342 /// Returns the metadata for the file that this entry points at.
1344 /// This function will not traverse symlinks if this entry points at a
1347 /// # Platform-specific behavior
1349 /// On Windows this function is cheap to call (no extra system calls
1350 /// needed), but on Unix platforms this function is the equivalent of
1351 /// calling `symlink_metadata` on the path.
1358 /// if let Ok(entries) = fs::read_dir(".") {
1359 /// for entry in entries {
1360 /// if let Ok(entry) = entry {
1361 /// // Here, `entry` is a `DirEntry`.
1362 /// if let Ok(metadata) = entry.metadata() {
1363 /// // Now let's show our entry's permissions!
1364 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1366 /// println!("Couldn't get metadata for {:?}", entry.path());
1372 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1373 pub fn metadata(&self) -> io::Result<Metadata> {
1374 self.0.metadata().map(Metadata)
1377 /// Returns the file type for the file that this entry points at.
1379 /// This function will not traverse symlinks if this entry points at a
1382 /// # Platform-specific behavior
1384 /// On Windows and most Unix platforms this function is free (no extra
1385 /// system calls needed), but some Unix platforms may require the equivalent
1386 /// call to `symlink_metadata` to learn about the target file type.
1393 /// if let Ok(entries) = fs::read_dir(".") {
1394 /// for entry in entries {
1395 /// if let Ok(entry) = entry {
1396 /// // Here, `entry` is a `DirEntry`.
1397 /// if let Ok(file_type) = entry.file_type() {
1398 /// // Now let's show our entry's file type!
1399 /// println!("{:?}: {:?}", entry.path(), file_type);
1401 /// println!("Couldn't get file type for {:?}", entry.path());
1407 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1408 pub fn file_type(&self) -> io::Result<FileType> {
1409 self.0.file_type().map(FileType)
1412 /// Returns the bare file name of this directory entry without any other
1413 /// leading path component.
1420 /// if let Ok(entries) = fs::read_dir(".") {
1421 /// for entry in entries {
1422 /// if let Ok(entry) = entry {
1423 /// // Here, `entry` is a `DirEntry`.
1424 /// println!("{:?}", entry.file_name());
1429 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1430 pub fn file_name(&self) -> OsString {
1435 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1436 impl fmt::Debug for DirEntry {
1437 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1438 f.debug_tuple("DirEntry")
1439 .field(&self.path())
1444 impl AsInner<fs_imp::DirEntry> for DirEntry {
1445 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
1448 /// Removes a file from the filesystem.
1450 /// Note that there is no
1451 /// guarantee that the file is immediately deleted (e.g., depending on
1452 /// platform, other open file descriptors may prevent immediate removal).
1454 /// # Platform-specific behavior
1456 /// This function currently corresponds to the `unlink` function on Unix
1457 /// and the `DeleteFile` function on Windows.
1458 /// Note that, this [may change in the future][changes].
1460 /// [changes]: ../io/index.html#platform-specific-behavior
1464 /// This function will return an error in the following situations, but is not
1465 /// limited to just these cases:
1467 /// * `path` points to a directory.
1468 /// * The user lacks permissions to remove the file.
1475 /// fn main() -> std::io::Result<()> {
1476 /// fs::remove_file("a.txt")?;
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1482 fs_imp::unlink(path.as_ref())
1485 /// Given a path, query the file system to get information about a file,
1488 /// This function will traverse symbolic links to query information about the
1489 /// destination file.
1491 /// # Platform-specific behavior
1493 /// This function currently corresponds to the `stat` function on Unix
1494 /// and the `GetFileAttributesEx` function on Windows.
1495 /// Note that, this [may change in the future][changes].
1497 /// [changes]: ../io/index.html#platform-specific-behavior
1501 /// This function will return an error in the following situations, but is not
1502 /// limited to just these cases:
1504 /// * The user lacks permissions to perform `metadata` call on `path`.
1505 /// * `path` does not exist.
1512 /// fn main() -> std::io::Result<()> {
1513 /// let attr = fs::metadata("/some/file/path.txt")?;
1514 /// // inspect attr ...
1518 #[stable(feature = "rust1", since = "1.0.0")]
1519 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1520 fs_imp::stat(path.as_ref()).map(Metadata)
1523 /// Query the metadata about a file without following symlinks.
1525 /// # Platform-specific behavior
1527 /// This function currently corresponds to the `lstat` function on Unix
1528 /// and the `GetFileAttributesEx` function on Windows.
1529 /// Note that, this [may change in the future][changes].
1531 /// [changes]: ../io/index.html#platform-specific-behavior
1535 /// This function will return an error in the following situations, but is not
1536 /// limited to just these cases:
1538 /// * The user lacks permissions to perform `metadata` call on `path`.
1539 /// * `path` does not exist.
1546 /// fn main() -> std::io::Result<()> {
1547 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1548 /// // inspect attr ...
1552 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1553 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1554 fs_imp::lstat(path.as_ref()).map(Metadata)
1557 /// Rename a file or directory to a new name, replacing the original file if
1558 /// `to` already exists.
1560 /// This will not work if the new name is on a different mount point.
1562 /// # Platform-specific behavior
1564 /// This function currently corresponds to the `rename` function on Unix
1565 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1567 /// Because of this, the behavior when both `from` and `to` exist differs. On
1568 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1569 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1570 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1572 /// Note that, this [may change in the future][changes].
1574 /// [changes]: ../io/index.html#platform-specific-behavior
1578 /// This function will return an error in the following situations, but is not
1579 /// limited to just these cases:
1581 /// * `from` does not exist.
1582 /// * The user lacks permissions to view contents.
1583 /// * `from` and `to` are on separate filesystems.
1590 /// fn main() -> std::io::Result<()> {
1591 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1595 #[stable(feature = "rust1", since = "1.0.0")]
1596 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1597 fs_imp::rename(from.as_ref(), to.as_ref())
1600 /// Copies the contents of one file to another. This function will also
1601 /// copy the permission bits of the original file to the destination file.
1603 /// This function will **overwrite** the contents of `to`.
1605 /// Note that if `from` and `to` both point to the same file, then the file
1606 /// will likely get truncated by this operation.
1608 /// On success, the total number of bytes copied is returned and it is equal to
1609 /// the length of the `to` file as reported by `metadata`.
1611 /// If you’re wanting to copy the contents of one file to another and you’re
1612 /// working with [`File`]s, see the [`io::copy`] function.
1614 /// [`io::copy`]: ../io/fn.copy.html
1615 /// [`File`]: ./struct.File.html
1617 /// # Platform-specific behavior
1619 /// This function currently corresponds to the `open` function in Unix
1620 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1621 /// `O_CLOEXEC` is set for returned file descriptors.
1622 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1623 /// NTFS streams are copied but only the size of the main stream is returned by
1624 /// this function. On MacOS, this function corresponds to `fclonefileat` and
1626 /// Note that, this [may change in the future][changes].
1628 /// [changes]: ../io/index.html#platform-specific-behavior
1632 /// This function will return an error in the following situations, but is not
1633 /// limited to just these cases:
1635 /// * The `from` path is not a file.
1636 /// * The `from` file does not exist.
1637 /// * The current process does not have the permission rights to access
1638 /// `from` or write `to`.
1645 /// fn main() -> std::io::Result<()> {
1646 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1650 #[stable(feature = "rust1", since = "1.0.0")]
1651 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1652 fs_imp::copy(from.as_ref(), to.as_ref())
1655 /// Creates a new hard link on the filesystem.
1657 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1658 /// often require these two paths to both be located on the same filesystem.
1660 /// # Platform-specific behavior
1662 /// This function currently corresponds to the `link` function on Unix
1663 /// and the `CreateHardLink` function on Windows.
1664 /// Note that, this [may change in the future][changes].
1666 /// [changes]: ../io/index.html#platform-specific-behavior
1670 /// This function will return an error in the following situations, but is not
1671 /// limited to just these cases:
1673 /// * The `src` path is not a file or doesn't exist.
1680 /// fn main() -> std::io::Result<()> {
1681 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1685 #[stable(feature = "rust1", since = "1.0.0")]
1686 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1687 fs_imp::link(src.as_ref(), dst.as_ref())
1690 /// Creates a new symbolic link on the filesystem.
1692 /// The `dst` path will be a symbolic link pointing to the `src` path.
1693 /// On Windows, this will be a file symlink, not a directory symlink;
1694 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1695 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1696 /// used instead to make the intent explicit.
1698 /// [`std::os::unix::fs::symlink`]: ../os/unix/fs/fn.symlink.html
1699 /// [`std::os::windows::fs::symlink_file`]: ../os/windows/fs/fn.symlink_file.html
1700 /// [`symlink_dir`]: ../os/windows/fs/fn.symlink_dir.html
1708 /// fn main() -> std::io::Result<()> {
1709 /// fs::soft_link("a.txt", "b.txt")?;
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 #[rustc_deprecated(since = "1.1.0",
1715 reason = "replaced with std::os::unix::fs::symlink and \
1716 std::os::windows::fs::{symlink_file, symlink_dir}")]
1717 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1718 fs_imp::symlink(src.as_ref(), dst.as_ref())
1721 /// Reads a symbolic link, returning the file that the link points to.
1723 /// # Platform-specific behavior
1725 /// This function currently corresponds to the `readlink` function on Unix
1726 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1727 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1728 /// Note that, this [may change in the future][changes].
1730 /// [changes]: ../io/index.html#platform-specific-behavior
1734 /// This function will return an error in the following situations, but is not
1735 /// limited to just these cases:
1737 /// * `path` is not a symbolic link.
1738 /// * `path` does not exist.
1745 /// fn main() -> std::io::Result<()> {
1746 /// let path = fs::read_link("a.txt")?;
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1752 fs_imp::readlink(path.as_ref())
1755 /// Returns the canonical, absolute form of a path with all intermediate
1756 /// components normalized and symbolic links resolved.
1758 /// # Platform-specific behavior
1760 /// This function currently corresponds to the `realpath` function on Unix
1761 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1762 /// Note that, this [may change in the future][changes].
1764 /// On Windows, this converts the path to use [extended length path][path]
1765 /// syntax, which allows your program to use longer path names, but means you
1766 /// can only join backslash-delimited paths to it, and it may be incompatible
1767 /// with other applications (if passed to the application on the command-line,
1768 /// or written to a file another application may read).
1770 /// [changes]: ../io/index.html#platform-specific-behavior
1771 /// [path]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
1775 /// This function will return an error in the following situations, but is not
1776 /// limited to just these cases:
1778 /// * `path` does not exist.
1779 /// * A non-final component in path is not a directory.
1786 /// fn main() -> std::io::Result<()> {
1787 /// let path = fs::canonicalize("../a/../foo.txt")?;
1791 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1792 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1793 fs_imp::canonicalize(path.as_ref())
1796 /// Creates a new, empty directory at the provided path
1798 /// # Platform-specific behavior
1800 /// This function currently corresponds to the `mkdir` function on Unix
1801 /// and the `CreateDirectory` function on Windows.
1802 /// Note that, this [may change in the future][changes].
1804 /// [changes]: ../io/index.html#platform-specific-behavior
1806 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1807 /// return an error. To create a directory and all its missing parents at the
1808 /// same time, use the [`create_dir_all`] function.
1812 /// This function will return an error in the following situations, but is not
1813 /// limited to just these cases:
1815 /// * User lacks permissions to create directory at `path`.
1816 /// * A parent of the given path doesn't exist. (To create a directory and all
1817 /// its missing parents at the same time, use the [`create_dir_all`]
1819 /// * `path` already exists.
1821 /// [`create_dir_all`]: fn.create_dir_all.html
1828 /// fn main() -> std::io::Result<()> {
1829 /// fs::create_dir("/some/dir")?;
1833 #[stable(feature = "rust1", since = "1.0.0")]
1834 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1835 DirBuilder::new().create(path.as_ref())
1838 /// Recursively create a directory and all of its parent components if they
1841 /// # Platform-specific behavior
1843 /// This function currently corresponds to the `mkdir` function on Unix
1844 /// and the `CreateDirectory` function on Windows.
1845 /// Note that, this [may change in the future][changes].
1847 /// [changes]: ../io/index.html#platform-specific-behavior
1851 /// This function will return an error in the following situations, but is not
1852 /// limited to just these cases:
1854 /// * If any directory in the path specified by `path`
1855 /// does not already exist and it could not be created otherwise. The specific
1856 /// error conditions for when a directory is being created (after it is
1857 /// determined to not exist) are outlined by [`fs::create_dir`].
1859 /// Notable exception is made for situations where any of the directories
1860 /// specified in the `path` could not be created as it was being created concurrently.
1861 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1862 /// concurrently from multiple threads or processes is guaranteed not to fail
1863 /// due to a race condition with itself.
1865 /// [`fs::create_dir`]: fn.create_dir.html
1872 /// fn main() -> std::io::Result<()> {
1873 /// fs::create_dir_all("/some/dir")?;
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1879 DirBuilder::new().recursive(true).create(path.as_ref())
1882 /// Removes an existing, empty directory.
1884 /// # Platform-specific behavior
1886 /// This function currently corresponds to the `rmdir` function on Unix
1887 /// and the `RemoveDirectory` function on Windows.
1888 /// Note that, this [may change in the future][changes].
1890 /// [changes]: ../io/index.html#platform-specific-behavior
1894 /// This function will return an error in the following situations, but is not
1895 /// limited to just these cases:
1897 /// * The user lacks permissions to remove the directory at the provided `path`.
1898 /// * The directory isn't empty.
1905 /// fn main() -> std::io::Result<()> {
1906 /// fs::remove_dir("/some/dir")?;
1910 #[stable(feature = "rust1", since = "1.0.0")]
1911 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1912 fs_imp::rmdir(path.as_ref())
1915 /// Removes a directory at this path, after removing all its contents. Use
1918 /// This function does **not** follow symbolic links and it will simply remove the
1919 /// symbolic link itself.
1921 /// # Platform-specific behavior
1923 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1924 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1926 /// Note that, this [may change in the future][changes].
1928 /// [changes]: ../io/index.html#platform-specific-behavior
1932 /// See [`fs::remove_file`] and [`fs::remove_dir`].
1934 /// [`fs::remove_file`]: fn.remove_file.html
1935 /// [`fs::remove_dir`]: fn.remove_dir.html
1942 /// fn main() -> std::io::Result<()> {
1943 /// fs::remove_dir_all("/some/dir")?;
1947 #[stable(feature = "rust1", since = "1.0.0")]
1948 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1949 fs_imp::remove_dir_all(path.as_ref())
1952 /// Returns an iterator over the entries within a directory.
1954 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
1955 /// New errors may be encountered after an iterator is initially constructed.
1957 /// [`io::Result`]: ../io/type.Result.html
1958 /// [`DirEntry`]: struct.DirEntry.html
1960 /// # Platform-specific behavior
1962 /// This function currently corresponds to the `opendir` function on Unix
1963 /// and the `FindFirstFile` function on Windows. Advancing the iterator
1964 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
1965 /// Note that, this [may change in the future][changes].
1967 /// [changes]: ../io/index.html#platform-specific-behavior
1969 /// The order in which this iterator returns entries is platform and filesystem
1974 /// This function will return an error in the following situations, but is not
1975 /// limited to just these cases:
1977 /// * The provided `path` doesn't exist.
1978 /// * The process lacks permissions to view the contents.
1979 /// * The `path` points at a non-directory file.
1985 /// use std::fs::{self, DirEntry};
1986 /// use std::path::Path;
1988 /// // one possible implementation of walking a directory only visiting files
1989 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
1990 /// if dir.is_dir() {
1991 /// for entry in fs::read_dir(dir)? {
1992 /// let entry = entry?;
1993 /// let path = entry.path();
1994 /// if path.is_dir() {
1995 /// visit_dirs(&path, cb)?;
2006 /// use std::{fs, io};
2008 /// fn main() -> io::Result<()> {
2009 /// let mut entries = fs::read_dir(".")?
2010 /// .map(|res| res.map(|e| e.path()))
2011 /// .collect::<Result<Vec<_>, io::Error>>()?;
2013 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2014 /// // ordering is required the entries should be explicitly sorted.
2018 /// // The entries have now been sorted by their path.
2023 #[stable(feature = "rust1", since = "1.0.0")]
2024 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2025 fs_imp::readdir(path.as_ref()).map(ReadDir)
2028 /// Changes the permissions found on a file or a directory.
2030 /// # Platform-specific behavior
2032 /// This function currently corresponds to the `chmod` function on Unix
2033 /// and the `SetFileAttributes` function on Windows.
2034 /// Note that, this [may change in the future][changes].
2036 /// [changes]: ../io/index.html#platform-specific-behavior
2040 /// This function will return an error in the following situations, but is not
2041 /// limited to just these cases:
2043 /// * `path` does not exist.
2044 /// * The user lacks the permission to change attributes of the file.
2051 /// fn main() -> std::io::Result<()> {
2052 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2053 /// perms.set_readonly(true);
2054 /// fs::set_permissions("foo.txt", perms)?;
2058 #[stable(feature = "set_permissions", since = "1.1.0")]
2059 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
2061 fs_imp::set_perm(path.as_ref(), perm.0)
2065 /// Creates a new set of options with default mode/security settings for all
2066 /// platforms and also non-recursive.
2071 /// use std::fs::DirBuilder;
2073 /// let builder = DirBuilder::new();
2075 #[stable(feature = "dir_builder", since = "1.6.0")]
2076 pub fn new() -> DirBuilder {
2078 inner: fs_imp::DirBuilder::new(),
2083 /// Indicates that directories should be created recursively, creating all
2084 /// parent directories. Parents that do not exist are created with the same
2085 /// security and permissions settings.
2087 /// This option defaults to `false`.
2092 /// use std::fs::DirBuilder;
2094 /// let mut builder = DirBuilder::new();
2095 /// builder.recursive(true);
2097 #[stable(feature = "dir_builder", since = "1.6.0")]
2098 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2099 self.recursive = recursive;
2103 /// Creates the specified directory with the options configured in this
2106 /// It is considered an error if the directory already exists unless
2107 /// recursive mode is enabled.
2112 /// use std::fs::{self, DirBuilder};
2114 /// let path = "/tmp/foo/bar/baz";
2115 /// DirBuilder::new()
2116 /// .recursive(true)
2117 /// .create(path).unwrap();
2119 /// assert!(fs::metadata(path).unwrap().is_dir());
2121 #[stable(feature = "dir_builder", since = "1.6.0")]
2122 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2123 self._create(path.as_ref())
2126 fn _create(&self, path: &Path) -> io::Result<()> {
2128 self.create_dir_all(path)
2130 self.inner.mkdir(path)
2134 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2135 if path == Path::new("") {
2139 match self.inner.mkdir(path) {
2140 Ok(()) => return Ok(()),
2141 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2142 Err(_) if path.is_dir() => return Ok(()),
2143 Err(e) => return Err(e),
2145 match path.parent() {
2146 Some(p) => self.create_dir_all(p)?,
2147 None => return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree")),
2149 match self.inner.mkdir(path) {
2151 Err(_) if path.is_dir() => Ok(()),
2157 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2158 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2163 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
2165 use crate::io::prelude::*;
2167 use crate::fs::{self, File, OpenOptions};
2168 use crate::io::{ErrorKind, SeekFrom};
2169 use crate::path::Path;
2171 use crate::sys_common::io::test::{TempDir, tmpdir};
2174 use rand::{rngs::StdRng, RngCore, SeedableRng};
2177 use crate::os::windows::fs::{symlink_dir, symlink_file};
2179 use crate::sys::fs::symlink_junction;
2181 use crate::os::unix::fs::symlink as symlink_dir;
2183 use crate::os::unix::fs::symlink as symlink_file;
2185 use crate::os::unix::fs::symlink as symlink_junction;
2187 macro_rules! check { ($e:expr) => (
2190 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
2195 macro_rules! error { ($e:expr, $s:expr) => (
2197 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2198 Err(ref err) => assert!(err.raw_os_error() == Some($s),
2199 format!("`{}` did not have a code of `{}`", err, $s))
2204 macro_rules! error { ($e:expr, $s:expr) => ( error_contains!($e, $s) ) }
2206 macro_rules! error_contains { ($e:expr, $s:expr) => (
2208 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2209 Err(ref err) => assert!(err.to_string().contains($s),
2210 format!("`{}` did not contain `{}`", err, $s))
2214 // Several test fail on windows if the user does not have permission to
2215 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
2216 // disabling these test on Windows, use this function to test whether we
2217 // have permission, and return otherwise. This way, we still don't run these
2218 // tests most of the time, but at least we do if the user has the right
2220 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
2221 if cfg!(unix) { return true }
2222 let link = tmpdir.join("some_hopefully_unique_link_name");
2224 match symlink_file(r"nonexisting_target", link) {
2226 // ERROR_PRIVILEGE_NOT_HELD = 1314
2227 Err(ref err) if err.raw_os_error() == Some(1314) => false,
2233 fn file_test_io_smoke_test() {
2234 let message = "it's alright. have a good time";
2235 let tmpdir = tmpdir();
2236 let filename = &tmpdir.join("file_rt_io_file_test.txt");
2238 let mut write_stream = check!(File::create(filename));
2239 check!(write_stream.write(message.as_bytes()));
2242 let mut read_stream = check!(File::open(filename));
2243 let mut read_buf = [0; 1028];
2244 let read_str = match check!(read_stream.read(&mut read_buf)) {
2245 0 => panic!("shouldn't happen"),
2246 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
2248 assert_eq!(read_str, message);
2250 check!(fs::remove_file(filename));
2254 fn invalid_path_raises() {
2255 let tmpdir = tmpdir();
2256 let filename = &tmpdir.join("file_that_does_not_exist.txt");
2257 let result = File::open(filename);
2260 error!(result, "No such file or directory");
2262 error!(result, 2); // ERROR_FILE_NOT_FOUND
2266 fn file_test_iounlinking_invalid_path_should_raise_condition() {
2267 let tmpdir = tmpdir();
2268 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
2270 let result = fs::remove_file(filename);
2273 error!(result, "No such file or directory");
2275 error!(result, 2); // ERROR_FILE_NOT_FOUND
2279 fn file_test_io_non_positional_read() {
2280 let message: &str = "ten-four";
2281 let mut read_mem = [0; 8];
2282 let tmpdir = tmpdir();
2283 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
2285 let mut rw_stream = check!(File::create(filename));
2286 check!(rw_stream.write(message.as_bytes()));
2289 let mut read_stream = check!(File::open(filename));
2291 let read_buf = &mut read_mem[0..4];
2292 check!(read_stream.read(read_buf));
2295 let read_buf = &mut read_mem[4..8];
2296 check!(read_stream.read(read_buf));
2299 check!(fs::remove_file(filename));
2300 let read_str = str::from_utf8(&read_mem).unwrap();
2301 assert_eq!(read_str, message);
2305 fn file_test_io_seek_and_tell_smoke_test() {
2306 let message = "ten-four";
2307 let mut read_mem = [0; 4];
2308 let set_cursor = 4 as u64;
2309 let tell_pos_pre_read;
2310 let tell_pos_post_read;
2311 let tmpdir = tmpdir();
2312 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
2314 let mut rw_stream = check!(File::create(filename));
2315 check!(rw_stream.write(message.as_bytes()));
2318 let mut read_stream = check!(File::open(filename));
2319 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
2320 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
2321 check!(read_stream.read(&mut read_mem));
2322 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
2324 check!(fs::remove_file(filename));
2325 let read_str = str::from_utf8(&read_mem).unwrap();
2326 assert_eq!(read_str, &message[4..8]);
2327 assert_eq!(tell_pos_pre_read, set_cursor);
2328 assert_eq!(tell_pos_post_read, message.len() as u64);
2332 fn file_test_io_seek_and_write() {
2333 let initial_msg = "food-is-yummy";
2334 let overwrite_msg = "-the-bar!!";
2335 let final_msg = "foo-the-bar!!";
2337 let mut read_mem = [0; 13];
2338 let tmpdir = tmpdir();
2339 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
2341 let mut rw_stream = check!(File::create(filename));
2342 check!(rw_stream.write(initial_msg.as_bytes()));
2343 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
2344 check!(rw_stream.write(overwrite_msg.as_bytes()));
2347 let mut read_stream = check!(File::open(filename));
2348 check!(read_stream.read(&mut read_mem));
2350 check!(fs::remove_file(filename));
2351 let read_str = str::from_utf8(&read_mem).unwrap();
2352 assert!(read_str == final_msg);
2356 fn file_test_io_seek_shakedown() {
2358 let initial_msg = "qwer-asdf-zxcv";
2359 let chunk_one: &str = "qwer";
2360 let chunk_two: &str = "asdf";
2361 let chunk_three: &str = "zxcv";
2362 let mut read_mem = [0; 4];
2363 let tmpdir = tmpdir();
2364 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2366 let mut rw_stream = check!(File::create(filename));
2367 check!(rw_stream.write(initial_msg.as_bytes()));
2370 let mut read_stream = check!(File::open(filename));
2372 check!(read_stream.seek(SeekFrom::End(-4)));
2373 check!(read_stream.read(&mut read_mem));
2374 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2376 check!(read_stream.seek(SeekFrom::Current(-9)));
2377 check!(read_stream.read(&mut read_mem));
2378 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2380 check!(read_stream.seek(SeekFrom::Start(0)));
2381 check!(read_stream.read(&mut read_mem));
2382 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2384 check!(fs::remove_file(filename));
2388 fn file_test_io_eof() {
2389 let tmpdir = tmpdir();
2390 let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2391 let mut buf = [0; 256];
2393 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2394 let mut rw = check!(oo.open(&filename));
2395 assert_eq!(check!(rw.read(&mut buf)), 0);
2396 assert_eq!(check!(rw.read(&mut buf)), 0);
2398 check!(fs::remove_file(&filename));
2403 fn file_test_io_read_write_at() {
2404 use crate::os::unix::fs::FileExt;
2406 let tmpdir = tmpdir();
2407 let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2408 let mut buf = [0; 256];
2409 let write1 = "asdf";
2410 let write2 = "qwer-";
2411 let write3 = "-zxcv";
2412 let content = "qwer-asdf-zxcv";
2414 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2415 let mut rw = check!(oo.open(&filename));
2416 assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2417 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2418 assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2419 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2420 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2421 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2422 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2423 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2424 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2425 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2426 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2427 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2428 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2429 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2430 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2431 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2432 assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2433 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2436 let mut read = check!(File::open(&filename));
2437 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2438 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2439 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2440 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2441 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2442 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2443 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2444 assert_eq!(check!(read.read(&mut buf)), write3.len());
2445 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2446 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2447 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2448 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2449 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2450 assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2451 assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2452 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2454 check!(fs::remove_file(&filename));
2459 fn set_get_unix_permissions() {
2460 use crate::os::unix::fs::PermissionsExt;
2462 let tmpdir = tmpdir();
2463 let filename = &tmpdir.join("set_get_unix_permissions");
2464 check!(fs::create_dir(filename));
2467 check!(fs::set_permissions(filename,
2468 fs::Permissions::from_mode(0)));
2469 let metadata0 = check!(fs::metadata(filename));
2470 assert_eq!(mask & metadata0.permissions().mode(), 0);
2472 check!(fs::set_permissions(filename,
2473 fs::Permissions::from_mode(0o1777)));
2474 let metadata1 = check!(fs::metadata(filename));
2475 assert_eq!(mask & metadata1.permissions().mode(), 0o1777);
2480 fn file_test_io_seek_read_write() {
2481 use crate::os::windows::fs::FileExt;
2483 let tmpdir = tmpdir();
2484 let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2485 let mut buf = [0; 256];
2486 let write1 = "asdf";
2487 let write2 = "qwer-";
2488 let write3 = "-zxcv";
2489 let content = "qwer-asdf-zxcv";
2491 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2492 let mut rw = check!(oo.open(&filename));
2493 assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2494 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2495 assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2496 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2497 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2498 assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2499 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2500 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2501 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2502 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2503 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2504 assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2505 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2506 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2507 assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2508 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2511 let mut read = check!(File::open(&filename));
2512 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2513 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2514 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2515 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2516 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2517 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2518 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2519 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2520 assert_eq!(check!(read.read(&mut buf)), write3.len());
2521 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2522 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2523 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2524 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2525 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2526 assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2527 assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2529 check!(fs::remove_file(&filename));
2533 fn file_test_stat_is_correct_on_is_file() {
2534 let tmpdir = tmpdir();
2535 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2537 let mut opts = OpenOptions::new();
2538 let mut fs = check!(opts.read(true).write(true)
2539 .create(true).open(filename));
2541 fs.write(msg.as_bytes()).unwrap();
2543 let fstat_res = check!(fs.metadata());
2544 assert!(fstat_res.is_file());
2546 let stat_res_fn = check!(fs::metadata(filename));
2547 assert!(stat_res_fn.is_file());
2548 let stat_res_meth = check!(filename.metadata());
2549 assert!(stat_res_meth.is_file());
2550 check!(fs::remove_file(filename));
2554 fn file_test_stat_is_correct_on_is_dir() {
2555 let tmpdir = tmpdir();
2556 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2557 check!(fs::create_dir(filename));
2558 let stat_res_fn = check!(fs::metadata(filename));
2559 assert!(stat_res_fn.is_dir());
2560 let stat_res_meth = check!(filename.metadata());
2561 assert!(stat_res_meth.is_dir());
2562 check!(fs::remove_dir(filename));
2566 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2567 let tmpdir = tmpdir();
2568 let dir = &tmpdir.join("fileinfo_false_on_dir");
2569 check!(fs::create_dir(dir));
2570 assert!(!dir.is_file());
2571 check!(fs::remove_dir(dir));
2575 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2576 let tmpdir = tmpdir();
2577 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2578 check!(check!(File::create(file)).write(b"foo"));
2579 assert!(file.exists());
2580 check!(fs::remove_file(file));
2581 assert!(!file.exists());
2585 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2586 let tmpdir = tmpdir();
2587 let dir = &tmpdir.join("before_and_after_dir");
2588 assert!(!dir.exists());
2589 check!(fs::create_dir(dir));
2590 assert!(dir.exists());
2591 assert!(dir.is_dir());
2592 check!(fs::remove_dir(dir));
2593 assert!(!dir.exists());
2597 fn file_test_directoryinfo_readdir() {
2598 let tmpdir = tmpdir();
2599 let dir = &tmpdir.join("di_readdir");
2600 check!(fs::create_dir(dir));
2603 let f = dir.join(&format!("{}.txt", n));
2604 let mut w = check!(File::create(&f));
2605 let msg_str = format!("{}{}", prefix, n.to_string());
2606 let msg = msg_str.as_bytes();
2607 check!(w.write(msg));
2609 let files = check!(fs::read_dir(dir));
2610 let mut mem = [0; 4];
2612 let f = f.unwrap().path();
2614 let n = f.file_stem().unwrap();
2615 check!(check!(File::open(&f)).read(&mut mem));
2616 let read_str = str::from_utf8(&mem).unwrap();
2617 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2618 assert_eq!(expected, read_str);
2620 check!(fs::remove_file(&f));
2622 check!(fs::remove_dir(dir));
2626 fn file_create_new_already_exists_error() {
2627 let tmpdir = tmpdir();
2628 let file = &tmpdir.join("file_create_new_error_exists");
2629 check!(fs::File::create(file));
2630 let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2631 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2635 fn mkdir_path_already_exists_error() {
2636 let tmpdir = tmpdir();
2637 let dir = &tmpdir.join("mkdir_error_twice");
2638 check!(fs::create_dir(dir));
2639 let e = fs::create_dir(dir).unwrap_err();
2640 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2644 fn recursive_mkdir() {
2645 let tmpdir = tmpdir();
2646 let dir = tmpdir.join("d1/d2");
2647 check!(fs::create_dir_all(&dir));
2648 assert!(dir.is_dir())
2652 fn recursive_mkdir_failure() {
2653 let tmpdir = tmpdir();
2654 let dir = tmpdir.join("d1");
2655 let file = dir.join("f1");
2657 check!(fs::create_dir_all(&dir));
2658 check!(File::create(&file));
2660 let result = fs::create_dir_all(&file);
2662 assert!(result.is_err());
2666 fn concurrent_recursive_mkdir() {
2669 let mut dir = dir.join("a");
2671 dir = dir.join("a");
2673 let mut join = vec!();
2675 let dir = dir.clone();
2676 join.push(thread::spawn(move || {
2677 check!(fs::create_dir_all(&dir));
2681 // No `Display` on result of `join()`
2682 join.drain(..).map(|join| join.join().unwrap()).count();
2687 fn recursive_mkdir_slash() {
2688 check!(fs::create_dir_all(Path::new("/")));
2692 fn recursive_mkdir_dot() {
2693 check!(fs::create_dir_all(Path::new(".")));
2697 fn recursive_mkdir_empty() {
2698 check!(fs::create_dir_all(Path::new("")));
2702 fn recursive_rmdir() {
2703 let tmpdir = tmpdir();
2704 let d1 = tmpdir.join("d1");
2705 let dt = d1.join("t");
2706 let dtt = dt.join("t");
2707 let d2 = tmpdir.join("d2");
2708 let canary = d2.join("do_not_delete");
2709 check!(fs::create_dir_all(&dtt));
2710 check!(fs::create_dir_all(&d2));
2711 check!(check!(File::create(&canary)).write(b"foo"));
2712 check!(symlink_junction(&d2, &dt.join("d2")));
2713 let _ = symlink_file(&canary, &d1.join("canary"));
2714 check!(fs::remove_dir_all(&d1));
2716 assert!(!d1.is_dir());
2717 assert!(canary.exists());
2721 fn recursive_rmdir_of_symlink() {
2722 // test we do not recursively delete a symlink but only dirs.
2723 let tmpdir = tmpdir();
2724 let link = tmpdir.join("d1");
2725 let dir = tmpdir.join("d2");
2726 let canary = dir.join("do_not_delete");
2727 check!(fs::create_dir_all(&dir));
2728 check!(check!(File::create(&canary)).write(b"foo"));
2729 check!(symlink_junction(&dir, &link));
2730 check!(fs::remove_dir_all(&link));
2732 assert!(!link.is_dir());
2733 assert!(canary.exists());
2737 // only Windows makes a distinction between file and directory symlinks.
2739 fn recursive_rmdir_of_file_symlink() {
2740 let tmpdir = tmpdir();
2741 if !got_symlink_permission(&tmpdir) { return };
2743 let f1 = tmpdir.join("f1");
2744 let f2 = tmpdir.join("f2");
2745 check!(check!(File::create(&f1)).write(b"foo"));
2746 check!(symlink_file(&f1, &f2));
2747 match fs::remove_dir_all(&f2) {
2748 Ok(..) => panic!("wanted a failure"),
2754 fn unicode_path_is_dir() {
2755 assert!(Path::new(".").is_dir());
2756 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2758 let tmpdir = tmpdir();
2760 let mut dirpath = tmpdir.path().to_path_buf();
2761 dirpath.push("test-가一ー你好");
2762 check!(fs::create_dir(&dirpath));
2763 assert!(dirpath.is_dir());
2765 let mut filepath = dirpath;
2766 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2767 check!(File::create(&filepath)); // ignore return; touch only
2768 assert!(!filepath.is_dir());
2769 assert!(filepath.exists());
2773 fn unicode_path_exists() {
2774 assert!(Path::new(".").exists());
2775 assert!(!Path::new("test/nonexistent-bogus-path").exists());
2777 let tmpdir = tmpdir();
2778 let unicode = tmpdir.path();
2779 let unicode = unicode.join("test-각丁ー再见");
2780 check!(fs::create_dir(&unicode));
2781 assert!(unicode.exists());
2782 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2786 fn copy_file_does_not_exist() {
2787 let from = Path::new("test/nonexistent-bogus-path");
2788 let to = Path::new("test/other-bogus-path");
2790 match fs::copy(&from, &to) {
2793 assert!(!from.exists());
2794 assert!(!to.exists());
2800 fn copy_src_does_not_exist() {
2801 let tmpdir = tmpdir();
2802 let from = Path::new("test/nonexistent-bogus-path");
2803 let to = tmpdir.join("out.txt");
2804 check!(check!(File::create(&to)).write(b"hello"));
2805 assert!(fs::copy(&from, &to).is_err());
2806 assert!(!from.exists());
2807 let mut v = Vec::new();
2808 check!(check!(File::open(&to)).read_to_end(&mut v));
2809 assert_eq!(v, b"hello");
2814 let tmpdir = tmpdir();
2815 let input = tmpdir.join("in.txt");
2816 let out = tmpdir.join("out.txt");
2818 check!(check!(File::create(&input)).write(b"hello"));
2819 check!(fs::copy(&input, &out));
2820 let mut v = Vec::new();
2821 check!(check!(File::open(&out)).read_to_end(&mut v));
2822 assert_eq!(v, b"hello");
2824 assert_eq!(check!(input.metadata()).permissions(),
2825 check!(out.metadata()).permissions());
2829 fn copy_file_dst_dir() {
2830 let tmpdir = tmpdir();
2831 let out = tmpdir.join("out");
2833 check!(File::create(&out));
2834 match fs::copy(&*out, tmpdir.path()) {
2835 Ok(..) => panic!(), Err(..) => {}
2840 fn copy_file_dst_exists() {
2841 let tmpdir = tmpdir();
2842 let input = tmpdir.join("in");
2843 let output = tmpdir.join("out");
2845 check!(check!(File::create(&input)).write("foo".as_bytes()));
2846 check!(check!(File::create(&output)).write("bar".as_bytes()));
2847 check!(fs::copy(&input, &output));
2849 let mut v = Vec::new();
2850 check!(check!(File::open(&output)).read_to_end(&mut v));
2851 assert_eq!(v, b"foo".to_vec());
2855 fn copy_file_src_dir() {
2856 let tmpdir = tmpdir();
2857 let out = tmpdir.join("out");
2859 match fs::copy(tmpdir.path(), &out) {
2860 Ok(..) => panic!(), Err(..) => {}
2862 assert!(!out.exists());
2866 fn copy_file_preserves_perm_bits() {
2867 let tmpdir = tmpdir();
2868 let input = tmpdir.join("in.txt");
2869 let out = tmpdir.join("out.txt");
2871 let attr = check!(check!(File::create(&input)).metadata());
2872 let mut p = attr.permissions();
2873 p.set_readonly(true);
2874 check!(fs::set_permissions(&input, p));
2875 check!(fs::copy(&input, &out));
2876 assert!(check!(out.metadata()).permissions().readonly());
2877 check!(fs::set_permissions(&input, attr.permissions()));
2878 check!(fs::set_permissions(&out, attr.permissions()));
2883 fn copy_file_preserves_streams() {
2885 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2886 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 0);
2887 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2888 let mut v = Vec::new();
2889 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2890 assert_eq!(v, b"carrot".to_vec());
2894 fn copy_file_returns_metadata_len() {
2896 let in_path = tmp.join("in.txt");
2897 let out_path = tmp.join("out.txt");
2898 check!(check!(File::create(&in_path)).write(b"lettuce"));
2900 check!(check!(File::create(tmp.join("in.txt:bunny"))).write(b"carrot"));
2901 let copied_len = check!(fs::copy(&in_path, &out_path));
2902 assert_eq!(check!(out_path.metadata()).len(), copied_len);
2906 fn copy_file_follows_dst_symlink() {
2908 if !got_symlink_permission(&tmp) { return };
2910 let in_path = tmp.join("in.txt");
2911 let out_path = tmp.join("out.txt");
2912 let out_path_symlink = tmp.join("out_symlink.txt");
2914 check!(fs::write(&in_path, "foo"));
2915 check!(fs::write(&out_path, "bar"));
2916 check!(symlink_file(&out_path, &out_path_symlink));
2918 check!(fs::copy(&in_path, &out_path_symlink));
2920 assert!(check!(out_path_symlink.symlink_metadata()).file_type().is_symlink());
2921 assert_eq!(check!(fs::read(&out_path_symlink)), b"foo".to_vec());
2922 assert_eq!(check!(fs::read(&out_path)), b"foo".to_vec());
2926 fn symlinks_work() {
2927 let tmpdir = tmpdir();
2928 if !got_symlink_permission(&tmpdir) { return };
2930 let input = tmpdir.join("in.txt");
2931 let out = tmpdir.join("out.txt");
2933 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2934 check!(symlink_file(&input, &out));
2935 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
2936 assert_eq!(check!(fs::metadata(&out)).len(),
2937 check!(fs::metadata(&input)).len());
2938 let mut v = Vec::new();
2939 check!(check!(File::open(&out)).read_to_end(&mut v));
2940 assert_eq!(v, b"foobar".to_vec());
2944 fn symlink_noexist() {
2945 // Symlinks can point to things that don't exist
2946 let tmpdir = tmpdir();
2947 if !got_symlink_permission(&tmpdir) { return };
2949 // Use a relative path for testing. Symlinks get normalized by Windows,
2950 // so we may not get the same path back for absolute paths
2951 check!(symlink_file(&"foo", &tmpdir.join("bar")));
2952 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(),
2959 // directory symlink
2960 assert_eq!(check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
2963 assert_eq!(check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
2964 r"C:\Users\Default");
2965 // junction with special permissions
2966 assert_eq!(check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
2969 let tmpdir = tmpdir();
2970 let link = tmpdir.join("link");
2971 if !got_symlink_permission(&tmpdir) { return };
2972 check!(symlink_file(&"foo", &link));
2973 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
2977 fn readlink_not_symlink() {
2978 let tmpdir = tmpdir();
2979 match fs::read_link(tmpdir.path()) {
2980 Ok(..) => panic!("wanted a failure"),
2987 let tmpdir = tmpdir();
2988 let input = tmpdir.join("in.txt");
2989 let out = tmpdir.join("out.txt");
2991 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2992 check!(fs::hard_link(&input, &out));
2993 assert_eq!(check!(fs::metadata(&out)).len(),
2994 check!(fs::metadata(&input)).len());
2995 assert_eq!(check!(fs::metadata(&out)).len(),
2996 check!(input.metadata()).len());
2997 let mut v = Vec::new();
2998 check!(check!(File::open(&out)).read_to_end(&mut v));
2999 assert_eq!(v, b"foobar".to_vec());
3001 // can't link to yourself
3002 match fs::hard_link(&input, &input) {
3003 Ok(..) => panic!("wanted a failure"),
3006 // can't link to something that doesn't exist
3007 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
3008 Ok(..) => panic!("wanted a failure"),
3015 let tmpdir = tmpdir();
3016 let file = tmpdir.join("in.txt");
3018 check!(File::create(&file));
3019 let attr = check!(fs::metadata(&file));
3020 assert!(!attr.permissions().readonly());
3021 let mut p = attr.permissions();
3022 p.set_readonly(true);
3023 check!(fs::set_permissions(&file, p.clone()));
3024 let attr = check!(fs::metadata(&file));
3025 assert!(attr.permissions().readonly());
3027 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
3028 Ok(..) => panic!("wanted an error"),
3032 p.set_readonly(false);
3033 check!(fs::set_permissions(&file, p));
3038 let tmpdir = tmpdir();
3039 let path = tmpdir.join("in.txt");
3041 let file = check!(File::create(&path));
3042 let attr = check!(fs::metadata(&path));
3043 assert!(!attr.permissions().readonly());
3044 let mut p = attr.permissions();
3045 p.set_readonly(true);
3046 check!(file.set_permissions(p.clone()));
3047 let attr = check!(fs::metadata(&path));
3048 assert!(attr.permissions().readonly());
3050 p.set_readonly(false);
3051 check!(file.set_permissions(p));
3055 fn sync_doesnt_kill_anything() {
3056 let tmpdir = tmpdir();
3057 let path = tmpdir.join("in.txt");
3059 let mut file = check!(File::create(&path));
3060 check!(file.sync_all());
3061 check!(file.sync_data());
3062 check!(file.write(b"foo"));
3063 check!(file.sync_all());
3064 check!(file.sync_data());
3068 fn truncate_works() {
3069 let tmpdir = tmpdir();
3070 let path = tmpdir.join("in.txt");
3072 let mut file = check!(File::create(&path));
3073 check!(file.write(b"foo"));
3074 check!(file.sync_all());
3076 // Do some simple things with truncation
3077 assert_eq!(check!(file.metadata()).len(), 3);
3078 check!(file.set_len(10));
3079 assert_eq!(check!(file.metadata()).len(), 10);
3080 check!(file.write(b"bar"));
3081 check!(file.sync_all());
3082 assert_eq!(check!(file.metadata()).len(), 10);
3084 let mut v = Vec::new();
3085 check!(check!(File::open(&path)).read_to_end(&mut v));
3086 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
3088 // Truncate to a smaller length, don't seek, and then write something.
3089 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
3090 // past the end of the file).
3091 check!(file.set_len(2));
3092 assert_eq!(check!(file.metadata()).len(), 2);
3093 check!(file.write(b"wut"));
3094 check!(file.sync_all());
3095 assert_eq!(check!(file.metadata()).len(), 9);
3096 let mut v = Vec::new();
3097 check!(check!(File::open(&path)).read_to_end(&mut v));
3098 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
3103 use crate::fs::OpenOptions as OO;
3104 fn c<T: Clone>(t: &T) -> T { t.clone() }
3106 let tmpdir = tmpdir();
3108 let mut r = OO::new(); r.read(true);
3109 let mut w = OO::new(); w.write(true);
3110 let mut rw = OO::new(); rw.read(true).write(true);
3111 let mut a = OO::new(); a.append(true);
3112 let mut ra = OO::new(); ra.read(true).append(true);
3115 let invalid_options = 87; // ERROR_INVALID_PARAMETER
3116 #[cfg(all(unix, not(target_os = "vxworks")))]
3117 let invalid_options = "Invalid argument";
3118 #[cfg(target_os = "vxworks")]
3119 let invalid_options = "invalid argument";
3121 // Test various combinations of creation modes and access modes.
3124 // creation mode | read | write | read-write | append | read-append |
3125 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
3126 // not set (open existing) | X | X | X | X | X |
3127 // create | | X | X | X | X |
3128 // truncate | | X | X | | |
3129 // create and truncate | | X | X | | |
3130 // create_new | | X | X | X | X |
3132 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
3135 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
3136 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
3137 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
3138 check!(c(&w).create(true).open(&tmpdir.join("a")));
3139 check!(c(&w).open(&tmpdir.join("a")));
3142 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
3143 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
3144 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
3145 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
3146 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
3149 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
3150 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
3151 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
3152 check!(c(&rw).create(true).open(&tmpdir.join("c")));
3153 check!(c(&rw).open(&tmpdir.join("c")));
3156 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
3157 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
3158 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
3159 check!(c(&a).create(true).open(&tmpdir.join("d")));
3160 check!(c(&a).open(&tmpdir.join("d")));
3163 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
3164 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
3165 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
3166 check!(c(&ra).create(true).open(&tmpdir.join("e")));
3167 check!(c(&ra).open(&tmpdir.join("e")));
3169 // Test opening a file without setting an access mode
3170 let mut blank = OO::new();
3171 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
3174 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
3176 // Test write fails for read-only
3177 check!(r.open(&tmpdir.join("h")));
3179 let mut f = check!(r.open(&tmpdir.join("h")));
3180 assert!(f.write("wut".as_bytes()).is_err());
3183 // Test write overwrites
3185 let mut f = check!(c(&w).open(&tmpdir.join("h")));
3186 check!(f.write("baz".as_bytes()));
3189 let mut f = check!(c(&r).open(&tmpdir.join("h")));
3190 let mut b = vec![0; 6];
3191 check!(f.read(&mut b));
3192 assert_eq!(b, "bazbar".as_bytes());
3195 // Test truncate works
3197 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
3198 check!(f.write("foo".as_bytes()));
3200 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3202 // Test append works
3203 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3205 let mut f = check!(c(&a).open(&tmpdir.join("h")));
3206 check!(f.write("bar".as_bytes()));
3208 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
3210 // Test .append(true) equals .write(true).append(true)
3212 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
3213 check!(f.write("baz".as_bytes()));
3215 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
3219 fn _assert_send_sync() {
3220 fn _assert_send_sync<T: Send + Sync>() {}
3221 _assert_send_sync::<OpenOptions>();
3226 let mut bytes = [0; 1024];
3227 StdRng::from_entropy().fill_bytes(&mut bytes);
3229 let tmpdir = tmpdir();
3231 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
3232 let mut v = Vec::new();
3233 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
3234 assert!(v == &bytes[..]);
3238 fn write_then_read() {
3239 let mut bytes = [0; 1024];
3240 StdRng::from_entropy().fill_bytes(&mut bytes);
3242 let tmpdir = tmpdir();
3244 check!(fs::write(&tmpdir.join("test"), &bytes[..]));
3245 let v = check!(fs::read(&tmpdir.join("test")));
3246 assert!(v == &bytes[..]);
3248 check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF]));
3249 error_contains!(fs::read_to_string(&tmpdir.join("not-utf8")),
3250 "stream did not contain valid UTF-8");
3253 check!(fs::write(&tmpdir.join("utf8"), s.as_bytes()));
3254 let string = check!(fs::read_to_string(&tmpdir.join("utf8")));
3255 assert_eq!(string, s);
3259 fn file_try_clone() {
3260 let tmpdir = tmpdir();
3262 let mut f1 = check!(OpenOptions::new()
3266 .open(&tmpdir.join("test")));
3267 let mut f2 = check!(f1.try_clone());
3269 check!(f1.write_all(b"hello world"));
3270 check!(f1.seek(SeekFrom::Start(2)));
3272 let mut buf = vec![];
3273 check!(f2.read_to_end(&mut buf));
3274 assert_eq!(buf, b"llo world");
3277 check!(f1.write_all(b"!"));
3281 #[cfg(not(windows))]
3282 fn unlink_readonly() {
3283 let tmpdir = tmpdir();
3284 let path = tmpdir.join("file");
3285 check!(File::create(&path));
3286 let mut perm = check!(fs::metadata(&path)).permissions();
3287 perm.set_readonly(true);
3288 check!(fs::set_permissions(&path, perm));
3289 check!(fs::remove_file(&path));
3293 fn mkdir_trailing_slash() {
3294 let tmpdir = tmpdir();
3295 let path = tmpdir.join("file");
3296 check!(fs::create_dir_all(&path.join("a/")));
3300 fn canonicalize_works_simple() {
3301 let tmpdir = tmpdir();
3302 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3303 let file = tmpdir.join("test");
3304 File::create(&file).unwrap();
3305 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3309 fn realpath_works() {
3310 let tmpdir = tmpdir();
3311 if !got_symlink_permission(&tmpdir) { return };
3313 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3314 let file = tmpdir.join("test");
3315 let dir = tmpdir.join("test2");
3316 let link = dir.join("link");
3317 let linkdir = tmpdir.join("test3");
3319 File::create(&file).unwrap();
3320 fs::create_dir(&dir).unwrap();
3321 symlink_file(&file, &link).unwrap();
3322 symlink_dir(&dir, &linkdir).unwrap();
3324 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
3326 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
3327 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3328 assert_eq!(fs::canonicalize(&link).unwrap(), file);
3329 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
3330 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
3334 fn realpath_works_tricky() {
3335 let tmpdir = tmpdir();
3336 if !got_symlink_permission(&tmpdir) { return };
3338 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3339 let a = tmpdir.join("a");
3340 let b = a.join("b");
3341 let c = b.join("c");
3342 let d = a.join("d");
3343 let e = d.join("e");
3344 let f = a.join("f");
3346 fs::create_dir_all(&b).unwrap();
3347 fs::create_dir_all(&d).unwrap();
3348 File::create(&f).unwrap();
3349 if cfg!(not(windows)) {
3350 symlink_file("../d/e", &c).unwrap();
3351 symlink_file("../f", &e).unwrap();
3354 symlink_file(r"..\d\e", &c).unwrap();
3355 symlink_file(r"..\f", &e).unwrap();
3358 assert_eq!(fs::canonicalize(&c).unwrap(), f);
3359 assert_eq!(fs::canonicalize(&e).unwrap(), f);
3363 fn dir_entry_methods() {
3364 let tmpdir = tmpdir();
3366 fs::create_dir_all(&tmpdir.join("a")).unwrap();
3367 File::create(&tmpdir.join("b")).unwrap();
3369 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
3370 let fname = file.file_name();
3371 match fname.to_str() {
3373 assert!(file.file_type().unwrap().is_dir());
3374 assert!(file.metadata().unwrap().is_dir());
3377 assert!(file.file_type().unwrap().is_file());
3378 assert!(file.metadata().unwrap().is_file());
3380 f => panic!("unknown file name: {:?}", f),
3386 fn dir_entry_debug() {
3387 let tmpdir = tmpdir();
3388 File::create(&tmpdir.join("b")).unwrap();
3389 let mut read_dir = tmpdir.path().read_dir().unwrap();
3390 let dir_entry = read_dir.next().unwrap().unwrap();
3391 let actual = format!("{:?}", dir_entry);
3392 let expected = format!("DirEntry({:?})", dir_entry.0.path());
3393 assert_eq!(actual, expected);
3397 fn read_dir_not_found() {
3398 let res = fs::read_dir("/path/that/does/not/exist");
3399 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
3403 fn create_dir_all_with_junctions() {
3404 let tmpdir = tmpdir();
3405 let target = tmpdir.join("target");
3407 let junction = tmpdir.join("junction");
3408 let b = junction.join("a/b");
3410 let link = tmpdir.join("link");
3411 let d = link.join("c/d");
3413 fs::create_dir(&target).unwrap();
3415 check!(symlink_junction(&target, &junction));
3416 check!(fs::create_dir_all(&b));
3417 // the junction itself is not a directory, but `is_dir()` on a Path
3419 assert!(junction.is_dir());
3420 assert!(b.exists());
3422 if !got_symlink_permission(&tmpdir) { return };
3423 check!(symlink_dir(&target, &link));
3424 check!(fs::create_dir_all(&d));
3425 assert!(link.is_dir());
3426 assert!(d.exists());
3430 fn metadata_access_times() {
3431 let tmpdir = tmpdir();
3433 let b = tmpdir.join("b");
3434 File::create(&b).unwrap();
3436 let a = check!(fs::metadata(&tmpdir.path()));
3437 let b = check!(fs::metadata(&b));
3439 assert_eq!(check!(a.accessed()), check!(a.accessed()));
3440 assert_eq!(check!(a.modified()), check!(a.modified()));
3441 assert_eq!(check!(b.accessed()), check!(b.modified()));
3443 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3444 check!(a.created());
3445 check!(b.created());
3448 if cfg!(target_os = "linux") {
3449 // Not always available
3450 match (a.created(), b.created()) {
3451 (Ok(t1), Ok(t2)) => assert!(t1 <= t2),
3452 (Err(e1), Err(e2)) if e1.kind() == ErrorKind::Other &&
3453 e2.kind() == ErrorKind::Other => {}
3455 "creation time must be always supported or not supported: {:?} {:?}",