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 `birthtime` field of `stat` on
1094 /// Unix platforms and the `ftCreationTime` field on Windows platforms.
1098 /// This field may not be available on all platforms, and will return an
1099 /// `Err` on platforms where it is not available.
1106 /// fn main() -> std::io::Result<()> {
1107 /// let metadata = fs::metadata("foo.txt")?;
1109 /// if let Ok(time) = metadata.created() {
1110 /// println!("{:?}", time);
1112 /// println!("Not supported on this platform");
1117 #[stable(feature = "fs_time", since = "1.10.0")]
1118 pub fn created(&self) -> io::Result<SystemTime> {
1119 self.0.created().map(FromInner::from_inner)
1123 #[stable(feature = "std_debug", since = "1.16.0")]
1124 impl fmt::Debug for Metadata {
1125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1126 f.debug_struct("Metadata")
1127 .field("file_type", &self.file_type())
1128 .field("is_dir", &self.is_dir())
1129 .field("is_file", &self.is_file())
1130 .field("permissions", &self.permissions())
1131 .field("modified", &self.modified())
1132 .field("accessed", &self.accessed())
1133 .field("created", &self.created())
1138 impl AsInner<fs_imp::FileAttr> for Metadata {
1139 fn as_inner(&self) -> &fs_imp::FileAttr { &self.0 }
1142 impl FromInner<fs_imp::FileAttr> for Metadata {
1143 fn from_inner(attr: fs_imp::FileAttr) -> Metadata { Metadata(attr) }
1147 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1152 /// use std::fs::File;
1154 /// fn main() -> std::io::Result<()> {
1155 /// let mut f = File::create("foo.txt")?;
1156 /// let metadata = f.metadata()?;
1158 /// assert_eq!(false, metadata.permissions().readonly());
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 pub fn readonly(&self) -> bool { self.0.readonly() }
1165 /// Modifies the readonly flag for this set of permissions. If the
1166 /// `readonly` argument is `true`, using the resulting `Permission` will
1167 /// update file permissions to forbid writing. Conversely, if it's `false`,
1168 /// using the resulting `Permission` will update file permissions to allow
1171 /// This operation does **not** modify the filesystem. To modify the
1172 /// filesystem use the [`fs::set_permissions`] function.
1174 /// [`fs::set_permissions`]: fn.set_permissions.html
1179 /// use std::fs::File;
1181 /// fn main() -> std::io::Result<()> {
1182 /// let f = File::create("foo.txt")?;
1183 /// let metadata = f.metadata()?;
1184 /// let mut permissions = metadata.permissions();
1186 /// permissions.set_readonly(true);
1188 /// // filesystem doesn't change
1189 /// assert_eq!(false, metadata.permissions().readonly());
1191 /// // just this particular `permissions`.
1192 /// assert_eq!(true, permissions.readonly());
1196 #[stable(feature = "rust1", since = "1.0.0")]
1197 pub fn set_readonly(&mut self, readonly: bool) {
1198 self.0.set_readonly(readonly)
1203 /// Tests whether this file type represents a directory. The
1204 /// result is mutually exclusive to the results of
1205 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1208 /// [`is_file`]: struct.FileType.html#method.is_file
1209 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1214 /// fn main() -> std::io::Result<()> {
1217 /// let metadata = fs::metadata("foo.txt")?;
1218 /// let file_type = metadata.file_type();
1220 /// assert_eq!(file_type.is_dir(), false);
1224 #[stable(feature = "file_type", since = "1.1.0")]
1225 pub fn is_dir(&self) -> bool { self.0.is_dir() }
1227 /// Tests whether this file type represents a regular file.
1228 /// The result is mutually exclusive to the results of
1229 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1232 /// [`is_dir`]: struct.FileType.html#method.is_dir
1233 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1238 /// fn main() -> std::io::Result<()> {
1241 /// let metadata = fs::metadata("foo.txt")?;
1242 /// let file_type = metadata.file_type();
1244 /// assert_eq!(file_type.is_file(), true);
1248 #[stable(feature = "file_type", since = "1.1.0")]
1249 pub fn is_file(&self) -> bool { self.0.is_file() }
1251 /// Tests whether this file type represents a symbolic link.
1252 /// The result is mutually exclusive to the results of
1253 /// [`is_dir`] and [`is_file`]; only zero or one of these
1256 /// The underlying [`Metadata`] struct needs to be retrieved
1257 /// with the [`fs::symlink_metadata`] function and not the
1258 /// [`fs::metadata`] function. The [`fs::metadata`] function
1259 /// follows symbolic links, so [`is_symlink`] would always
1260 /// return `false` for the target file.
1262 /// [`Metadata`]: struct.Metadata.html
1263 /// [`fs::metadata`]: fn.metadata.html
1264 /// [`fs::symlink_metadata`]: fn.symlink_metadata.html
1265 /// [`is_dir`]: struct.FileType.html#method.is_dir
1266 /// [`is_file`]: struct.FileType.html#method.is_file
1267 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1274 /// fn main() -> std::io::Result<()> {
1275 /// let metadata = fs::symlink_metadata("foo.txt")?;
1276 /// let file_type = metadata.file_type();
1278 /// assert_eq!(file_type.is_symlink(), false);
1282 #[stable(feature = "file_type", since = "1.1.0")]
1283 pub fn is_symlink(&self) -> bool { self.0.is_symlink() }
1286 impl AsInner<fs_imp::FileType> for FileType {
1287 fn as_inner(&self) -> &fs_imp::FileType { &self.0 }
1290 impl FromInner<fs_imp::FilePermissions> for Permissions {
1291 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1296 impl AsInner<fs_imp::FilePermissions> for Permissions {
1297 fn as_inner(&self) -> &fs_imp::FilePermissions { &self.0 }
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 impl Iterator for ReadDir {
1302 type Item = io::Result<DirEntry>;
1304 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1305 self.0.next().map(|entry| entry.map(DirEntry))
1310 /// Returns the full path to the file that this entry represents.
1312 /// The full path is created by joining the original path to `read_dir`
1313 /// with the filename of this entry.
1320 /// fn main() -> std::io::Result<()> {
1321 /// for entry in fs::read_dir(".")? {
1322 /// let dir = entry?;
1323 /// println!("{:?}", dir.path());
1329 /// This prints output like:
1332 /// "./whatever.txt"
1334 /// "./hello_world.rs"
1337 /// The exact text, of course, depends on what files you have in `.`.
1338 #[stable(feature = "rust1", since = "1.0.0")]
1339 pub fn path(&self) -> PathBuf { self.0.path() }
1341 /// Returns the metadata for the file that this entry points at.
1343 /// This function will not traverse symlinks if this entry points at a
1346 /// # Platform-specific behavior
1348 /// On Windows this function is cheap to call (no extra system calls
1349 /// needed), but on Unix platforms this function is the equivalent of
1350 /// calling `symlink_metadata` on the path.
1357 /// if let Ok(entries) = fs::read_dir(".") {
1358 /// for entry in entries {
1359 /// if let Ok(entry) = entry {
1360 /// // Here, `entry` is a `DirEntry`.
1361 /// if let Ok(metadata) = entry.metadata() {
1362 /// // Now let's show our entry's permissions!
1363 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1365 /// println!("Couldn't get metadata for {:?}", entry.path());
1371 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1372 pub fn metadata(&self) -> io::Result<Metadata> {
1373 self.0.metadata().map(Metadata)
1376 /// Returns the file type for the file that this entry points at.
1378 /// This function will not traverse symlinks if this entry points at a
1381 /// # Platform-specific behavior
1383 /// On Windows and most Unix platforms this function is free (no extra
1384 /// system calls needed), but some Unix platforms may require the equivalent
1385 /// call to `symlink_metadata` to learn about the target file type.
1392 /// if let Ok(entries) = fs::read_dir(".") {
1393 /// for entry in entries {
1394 /// if let Ok(entry) = entry {
1395 /// // Here, `entry` is a `DirEntry`.
1396 /// if let Ok(file_type) = entry.file_type() {
1397 /// // Now let's show our entry's file type!
1398 /// println!("{:?}: {:?}", entry.path(), file_type);
1400 /// println!("Couldn't get file type for {:?}", entry.path());
1406 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1407 pub fn file_type(&self) -> io::Result<FileType> {
1408 self.0.file_type().map(FileType)
1411 /// Returns the bare file name of this directory entry without any other
1412 /// leading path component.
1419 /// if let Ok(entries) = fs::read_dir(".") {
1420 /// for entry in entries {
1421 /// if let Ok(entry) = entry {
1422 /// // Here, `entry` is a `DirEntry`.
1423 /// println!("{:?}", entry.file_name());
1428 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1429 pub fn file_name(&self) -> OsString {
1434 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1435 impl fmt::Debug for DirEntry {
1436 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1437 f.debug_tuple("DirEntry")
1438 .field(&self.path())
1443 impl AsInner<fs_imp::DirEntry> for DirEntry {
1444 fn as_inner(&self) -> &fs_imp::DirEntry { &self.0 }
1447 /// Removes a file from the filesystem.
1449 /// Note that there is no
1450 /// guarantee that the file is immediately deleted (e.g., depending on
1451 /// platform, other open file descriptors may prevent immediate removal).
1453 /// # Platform-specific behavior
1455 /// This function currently corresponds to the `unlink` function on Unix
1456 /// and the `DeleteFile` function on Windows.
1457 /// Note that, this [may change in the future][changes].
1459 /// [changes]: ../io/index.html#platform-specific-behavior
1463 /// This function will return an error in the following situations, but is not
1464 /// limited to just these cases:
1466 /// * `path` points to a directory.
1467 /// * The user lacks permissions to remove the file.
1474 /// fn main() -> std::io::Result<()> {
1475 /// fs::remove_file("a.txt")?;
1479 #[stable(feature = "rust1", since = "1.0.0")]
1480 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1481 fs_imp::unlink(path.as_ref())
1484 /// Given a path, query the file system to get information about a file,
1487 /// This function will traverse symbolic links to query information about the
1488 /// destination file.
1490 /// # Platform-specific behavior
1492 /// This function currently corresponds to the `stat` function on Unix
1493 /// and the `GetFileAttributesEx` function on Windows.
1494 /// Note that, this [may change in the future][changes].
1496 /// [changes]: ../io/index.html#platform-specific-behavior
1500 /// This function will return an error in the following situations, but is not
1501 /// limited to just these cases:
1503 /// * The user lacks permissions to perform `metadata` call on `path`.
1504 /// * `path` does not exist.
1511 /// fn main() -> std::io::Result<()> {
1512 /// let attr = fs::metadata("/some/file/path.txt")?;
1513 /// // inspect attr ...
1517 #[stable(feature = "rust1", since = "1.0.0")]
1518 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1519 fs_imp::stat(path.as_ref()).map(Metadata)
1522 /// Query the metadata about a file without following symlinks.
1524 /// # Platform-specific behavior
1526 /// This function currently corresponds to the `lstat` function on Unix
1527 /// and the `GetFileAttributesEx` function on Windows.
1528 /// Note that, this [may change in the future][changes].
1530 /// [changes]: ../io/index.html#platform-specific-behavior
1534 /// This function will return an error in the following situations, but is not
1535 /// limited to just these cases:
1537 /// * The user lacks permissions to perform `metadata` call on `path`.
1538 /// * `path` does not exist.
1545 /// fn main() -> std::io::Result<()> {
1546 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1547 /// // inspect attr ...
1551 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1552 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1553 fs_imp::lstat(path.as_ref()).map(Metadata)
1556 /// Rename a file or directory to a new name, replacing the original file if
1557 /// `to` already exists.
1559 /// This will not work if the new name is on a different mount point.
1561 /// # Platform-specific behavior
1563 /// This function currently corresponds to the `rename` function on Unix
1564 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1566 /// Because of this, the behavior when both `from` and `to` exist differs. On
1567 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1568 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1569 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1571 /// Note that, this [may change in the future][changes].
1573 /// [changes]: ../io/index.html#platform-specific-behavior
1577 /// This function will return an error in the following situations, but is not
1578 /// limited to just these cases:
1580 /// * `from` does not exist.
1581 /// * The user lacks permissions to view contents.
1582 /// * `from` and `to` are on separate filesystems.
1589 /// fn main() -> std::io::Result<()> {
1590 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1594 #[stable(feature = "rust1", since = "1.0.0")]
1595 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1596 fs_imp::rename(from.as_ref(), to.as_ref())
1599 /// Copies the contents of one file to another. This function will also
1600 /// copy the permission bits of the original file to the destination file.
1602 /// This function will **overwrite** the contents of `to`.
1604 /// Note that if `from` and `to` both point to the same file, then the file
1605 /// will likely get truncated by this operation.
1607 /// On success, the total number of bytes copied is returned and it is equal to
1608 /// the length of the `to` file as reported by `metadata`.
1610 /// If you’re wanting to copy the contents of one file to another and you’re
1611 /// working with [`File`]s, see the [`io::copy`] function.
1613 /// [`io::copy`]: ../io/fn.copy.html
1614 /// [`File`]: ./struct.File.html
1616 /// # Platform-specific behavior
1618 /// This function currently corresponds to the `open` function in Unix
1619 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1620 /// `O_CLOEXEC` is set for returned file descriptors.
1621 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1622 /// NTFS streams are copied but only the size of the main stream is returned by
1623 /// this function. On MacOS, this function corresponds to `fclonefileat` and
1625 /// Note that, this [may change in the future][changes].
1627 /// [changes]: ../io/index.html#platform-specific-behavior
1631 /// This function will return an error in the following situations, but is not
1632 /// limited to just these cases:
1634 /// * The `from` path is not a file.
1635 /// * The `from` file does not exist.
1636 /// * The current process does not have the permission rights to access
1637 /// `from` or write `to`.
1644 /// fn main() -> std::io::Result<()> {
1645 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1649 #[stable(feature = "rust1", since = "1.0.0")]
1650 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1651 fs_imp::copy(from.as_ref(), to.as_ref())
1654 /// Creates a new hard link on the filesystem.
1656 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1657 /// often require these two paths to both be located on the same filesystem.
1659 /// # Platform-specific behavior
1661 /// This function currently corresponds to the `link` function on Unix
1662 /// and the `CreateHardLink` function on Windows.
1663 /// Note that, this [may change in the future][changes].
1665 /// [changes]: ../io/index.html#platform-specific-behavior
1669 /// This function will return an error in the following situations, but is not
1670 /// limited to just these cases:
1672 /// * The `src` path is not a file or doesn't exist.
1679 /// fn main() -> std::io::Result<()> {
1680 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1684 #[stable(feature = "rust1", since = "1.0.0")]
1685 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1686 fs_imp::link(src.as_ref(), dst.as_ref())
1689 /// Creates a new symbolic link on the filesystem.
1691 /// The `dst` path will be a symbolic link pointing to the `src` path.
1692 /// On Windows, this will be a file symlink, not a directory symlink;
1693 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1694 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1695 /// used instead to make the intent explicit.
1697 /// [`std::os::unix::fs::symlink`]: ../os/unix/fs/fn.symlink.html
1698 /// [`std::os::windows::fs::symlink_file`]: ../os/windows/fs/fn.symlink_file.html
1699 /// [`symlink_dir`]: ../os/windows/fs/fn.symlink_dir.html
1707 /// fn main() -> std::io::Result<()> {
1708 /// fs::soft_link("a.txt", "b.txt")?;
1712 #[stable(feature = "rust1", since = "1.0.0")]
1713 #[rustc_deprecated(since = "1.1.0",
1714 reason = "replaced with std::os::unix::fs::symlink and \
1715 std::os::windows::fs::{symlink_file, symlink_dir}")]
1716 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1717 fs_imp::symlink(src.as_ref(), dst.as_ref())
1720 /// Reads a symbolic link, returning the file that the link points to.
1722 /// # Platform-specific behavior
1724 /// This function currently corresponds to the `readlink` function on Unix
1725 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1726 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1727 /// Note that, this [may change in the future][changes].
1729 /// [changes]: ../io/index.html#platform-specific-behavior
1733 /// This function will return an error in the following situations, but is not
1734 /// limited to just these cases:
1736 /// * `path` is not a symbolic link.
1737 /// * `path` does not exist.
1744 /// fn main() -> std::io::Result<()> {
1745 /// let path = fs::read_link("a.txt")?;
1749 #[stable(feature = "rust1", since = "1.0.0")]
1750 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1751 fs_imp::readlink(path.as_ref())
1754 /// Returns the canonical, absolute form of a path with all intermediate
1755 /// components normalized and symbolic links resolved.
1757 /// # Platform-specific behavior
1759 /// This function currently corresponds to the `realpath` function on Unix
1760 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1761 /// Note that, this [may change in the future][changes].
1763 /// On Windows, this converts the path to use [extended length path][path]
1764 /// syntax, which allows your program to use longer path names, but means you
1765 /// can only join backslash-delimited paths to it, and it may be incompatible
1766 /// with other applications (if passed to the application on the command-line,
1767 /// or written to a file another application may read).
1769 /// [changes]: ../io/index.html#platform-specific-behavior
1770 /// [path]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
1774 /// This function will return an error in the following situations, but is not
1775 /// limited to just these cases:
1777 /// * `path` does not exist.
1778 /// * A non-final component in path is not a directory.
1785 /// fn main() -> std::io::Result<()> {
1786 /// let path = fs::canonicalize("../a/../foo.txt")?;
1790 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1791 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1792 fs_imp::canonicalize(path.as_ref())
1795 /// Creates a new, empty directory at the provided path
1797 /// # Platform-specific behavior
1799 /// This function currently corresponds to the `mkdir` function on Unix
1800 /// and the `CreateDirectory` function on Windows.
1801 /// Note that, this [may change in the future][changes].
1803 /// [changes]: ../io/index.html#platform-specific-behavior
1805 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1806 /// return an error. To create a directory and all its missing parents at the
1807 /// same time, use the [`create_dir_all`] function.
1811 /// This function will return an error in the following situations, but is not
1812 /// limited to just these cases:
1814 /// * User lacks permissions to create directory at `path`.
1815 /// * A parent of the given path doesn't exist. (To create a directory and all
1816 /// its missing parents at the same time, use the [`create_dir_all`]
1818 /// * `path` already exists.
1820 /// [`create_dir_all`]: fn.create_dir_all.html
1827 /// fn main() -> std::io::Result<()> {
1828 /// fs::create_dir("/some/dir")?;
1832 #[stable(feature = "rust1", since = "1.0.0")]
1833 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1834 DirBuilder::new().create(path.as_ref())
1837 /// Recursively create a directory and all of its parent components if they
1840 /// # Platform-specific behavior
1842 /// This function currently corresponds to the `mkdir` function on Unix
1843 /// and the `CreateDirectory` function on Windows.
1844 /// Note that, this [may change in the future][changes].
1846 /// [changes]: ../io/index.html#platform-specific-behavior
1850 /// This function will return an error in the following situations, but is not
1851 /// limited to just these cases:
1853 /// * If any directory in the path specified by `path`
1854 /// does not already exist and it could not be created otherwise. The specific
1855 /// error conditions for when a directory is being created (after it is
1856 /// determined to not exist) are outlined by [`fs::create_dir`].
1858 /// Notable exception is made for situations where any of the directories
1859 /// specified in the `path` could not be created as it was being created concurrently.
1860 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1861 /// concurrently from multiple threads or processes is guaranteed not to fail
1862 /// due to a race condition with itself.
1864 /// [`fs::create_dir`]: fn.create_dir.html
1871 /// fn main() -> std::io::Result<()> {
1872 /// fs::create_dir_all("/some/dir")?;
1876 #[stable(feature = "rust1", since = "1.0.0")]
1877 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1878 DirBuilder::new().recursive(true).create(path.as_ref())
1881 /// Removes an existing, empty directory.
1883 /// # Platform-specific behavior
1885 /// This function currently corresponds to the `rmdir` function on Unix
1886 /// and the `RemoveDirectory` function on Windows.
1887 /// Note that, this [may change in the future][changes].
1889 /// [changes]: ../io/index.html#platform-specific-behavior
1893 /// This function will return an error in the following situations, but is not
1894 /// limited to just these cases:
1896 /// * The user lacks permissions to remove the directory at the provided `path`.
1897 /// * The directory isn't empty.
1904 /// fn main() -> std::io::Result<()> {
1905 /// fs::remove_dir("/some/dir")?;
1909 #[stable(feature = "rust1", since = "1.0.0")]
1910 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1911 fs_imp::rmdir(path.as_ref())
1914 /// Removes a directory at this path, after removing all its contents. Use
1917 /// This function does **not** follow symbolic links and it will simply remove the
1918 /// symbolic link itself.
1920 /// # Platform-specific behavior
1922 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
1923 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
1925 /// Note that, this [may change in the future][changes].
1927 /// [changes]: ../io/index.html#platform-specific-behavior
1931 /// See [`fs::remove_file`] and [`fs::remove_dir`].
1933 /// [`fs::remove_file`]: fn.remove_file.html
1934 /// [`fs::remove_dir`]: fn.remove_dir.html
1941 /// fn main() -> std::io::Result<()> {
1942 /// fs::remove_dir_all("/some/dir")?;
1946 #[stable(feature = "rust1", since = "1.0.0")]
1947 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1948 fs_imp::remove_dir_all(path.as_ref())
1951 /// Returns an iterator over the entries within a directory.
1953 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
1954 /// New errors may be encountered after an iterator is initially constructed.
1956 /// [`io::Result`]: ../io/type.Result.html
1957 /// [`DirEntry`]: struct.DirEntry.html
1959 /// # Platform-specific behavior
1961 /// This function currently corresponds to the `opendir` function on Unix
1962 /// and the `FindFirstFile` function on Windows. Advancing the iterator
1963 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
1964 /// Note that, this [may change in the future][changes].
1966 /// [changes]: ../io/index.html#platform-specific-behavior
1968 /// The order in which this iterator returns entries is platform and filesystem
1973 /// This function will return an error in the following situations, but is not
1974 /// limited to just these cases:
1976 /// * The provided `path` doesn't exist.
1977 /// * The process lacks permissions to view the contents.
1978 /// * The `path` points at a non-directory file.
1984 /// use std::fs::{self, DirEntry};
1985 /// use std::path::Path;
1987 /// // one possible implementation of walking a directory only visiting files
1988 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
1989 /// if dir.is_dir() {
1990 /// for entry in fs::read_dir(dir)? {
1991 /// let entry = entry?;
1992 /// let path = entry.path();
1993 /// if path.is_dir() {
1994 /// visit_dirs(&path, cb)?;
2005 /// use std::{fs, io};
2007 /// fn main() -> io::Result<()> {
2008 /// let mut entries = fs::read_dir(".")?
2009 /// .map(|res| res.map(|e| e.path()))
2010 /// .collect::<Result<Vec<_>, io::Error>>()?;
2012 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2013 /// // ordering is required the entries should be explicitly sorted.
2017 /// // The entries have now been sorted by their path.
2022 #[stable(feature = "rust1", since = "1.0.0")]
2023 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2024 fs_imp::readdir(path.as_ref()).map(ReadDir)
2027 /// Changes the permissions found on a file or a directory.
2029 /// # Platform-specific behavior
2031 /// This function currently corresponds to the `chmod` function on Unix
2032 /// and the `SetFileAttributes` function on Windows.
2033 /// Note that, this [may change in the future][changes].
2035 /// [changes]: ../io/index.html#platform-specific-behavior
2039 /// This function will return an error in the following situations, but is not
2040 /// limited to just these cases:
2042 /// * `path` does not exist.
2043 /// * The user lacks the permission to change attributes of the file.
2050 /// fn main() -> std::io::Result<()> {
2051 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2052 /// perms.set_readonly(true);
2053 /// fs::set_permissions("foo.txt", perms)?;
2057 #[stable(feature = "set_permissions", since = "1.1.0")]
2058 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions)
2060 fs_imp::set_perm(path.as_ref(), perm.0)
2064 /// Creates a new set of options with default mode/security settings for all
2065 /// platforms and also non-recursive.
2070 /// use std::fs::DirBuilder;
2072 /// let builder = DirBuilder::new();
2074 #[stable(feature = "dir_builder", since = "1.6.0")]
2075 pub fn new() -> DirBuilder {
2077 inner: fs_imp::DirBuilder::new(),
2082 /// Indicates that directories should be created recursively, creating all
2083 /// parent directories. Parents that do not exist are created with the same
2084 /// security and permissions settings.
2086 /// This option defaults to `false`.
2091 /// use std::fs::DirBuilder;
2093 /// let mut builder = DirBuilder::new();
2094 /// builder.recursive(true);
2096 #[stable(feature = "dir_builder", since = "1.6.0")]
2097 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2098 self.recursive = recursive;
2102 /// Creates the specified directory with the options configured in this
2105 /// It is considered an error if the directory already exists unless
2106 /// recursive mode is enabled.
2111 /// use std::fs::{self, DirBuilder};
2113 /// let path = "/tmp/foo/bar/baz";
2114 /// DirBuilder::new()
2115 /// .recursive(true)
2116 /// .create(path).unwrap();
2118 /// assert!(fs::metadata(path).unwrap().is_dir());
2120 #[stable(feature = "dir_builder", since = "1.6.0")]
2121 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2122 self._create(path.as_ref())
2125 fn _create(&self, path: &Path) -> io::Result<()> {
2127 self.create_dir_all(path)
2129 self.inner.mkdir(path)
2133 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2134 if path == Path::new("") {
2138 match self.inner.mkdir(path) {
2139 Ok(()) => return Ok(()),
2140 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2141 Err(_) if path.is_dir() => return Ok(()),
2142 Err(e) => return Err(e),
2144 match path.parent() {
2145 Some(p) => self.create_dir_all(p)?,
2146 None => return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree")),
2148 match self.inner.mkdir(path) {
2150 Err(_) if path.is_dir() => Ok(()),
2156 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2157 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2162 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
2164 use crate::io::prelude::*;
2166 use crate::fs::{self, File, OpenOptions};
2167 use crate::io::{ErrorKind, SeekFrom};
2168 use crate::path::Path;
2170 use crate::sys_common::io::test::{TempDir, tmpdir};
2173 use rand::{rngs::StdRng, RngCore, SeedableRng};
2176 use crate::os::windows::fs::{symlink_dir, symlink_file};
2178 use crate::sys::fs::symlink_junction;
2180 use crate::os::unix::fs::symlink as symlink_dir;
2182 use crate::os::unix::fs::symlink as symlink_file;
2184 use crate::os::unix::fs::symlink as symlink_junction;
2186 macro_rules! check { ($e:expr) => (
2189 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
2194 macro_rules! error { ($e:expr, $s:expr) => (
2196 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2197 Err(ref err) => assert!(err.raw_os_error() == Some($s),
2198 format!("`{}` did not have a code of `{}`", err, $s))
2203 macro_rules! error { ($e:expr, $s:expr) => ( error_contains!($e, $s) ) }
2205 macro_rules! error_contains { ($e:expr, $s:expr) => (
2207 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2208 Err(ref err) => assert!(err.to_string().contains($s),
2209 format!("`{}` did not contain `{}`", err, $s))
2213 // Several test fail on windows if the user does not have permission to
2214 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
2215 // disabling these test on Windows, use this function to test whether we
2216 // have permission, and return otherwise. This way, we still don't run these
2217 // tests most of the time, but at least we do if the user has the right
2219 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
2220 if cfg!(unix) { return true }
2221 let link = tmpdir.join("some_hopefully_unique_link_name");
2223 match symlink_file(r"nonexisting_target", link) {
2225 // ERROR_PRIVILEGE_NOT_HELD = 1314
2226 Err(ref err) if err.raw_os_error() == Some(1314) => false,
2232 fn file_test_io_smoke_test() {
2233 let message = "it's alright. have a good time";
2234 let tmpdir = tmpdir();
2235 let filename = &tmpdir.join("file_rt_io_file_test.txt");
2237 let mut write_stream = check!(File::create(filename));
2238 check!(write_stream.write(message.as_bytes()));
2241 let mut read_stream = check!(File::open(filename));
2242 let mut read_buf = [0; 1028];
2243 let read_str = match check!(read_stream.read(&mut read_buf)) {
2244 0 => panic!("shouldn't happen"),
2245 n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
2247 assert_eq!(read_str, message);
2249 check!(fs::remove_file(filename));
2253 fn invalid_path_raises() {
2254 let tmpdir = tmpdir();
2255 let filename = &tmpdir.join("file_that_does_not_exist.txt");
2256 let result = File::open(filename);
2259 error!(result, "No such file or directory");
2261 error!(result, 2); // ERROR_FILE_NOT_FOUND
2265 fn file_test_iounlinking_invalid_path_should_raise_condition() {
2266 let tmpdir = tmpdir();
2267 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
2269 let result = fs::remove_file(filename);
2272 error!(result, "No such file or directory");
2274 error!(result, 2); // ERROR_FILE_NOT_FOUND
2278 fn file_test_io_non_positional_read() {
2279 let message: &str = "ten-four";
2280 let mut read_mem = [0; 8];
2281 let tmpdir = tmpdir();
2282 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
2284 let mut rw_stream = check!(File::create(filename));
2285 check!(rw_stream.write(message.as_bytes()));
2288 let mut read_stream = check!(File::open(filename));
2290 let read_buf = &mut read_mem[0..4];
2291 check!(read_stream.read(read_buf));
2294 let read_buf = &mut read_mem[4..8];
2295 check!(read_stream.read(read_buf));
2298 check!(fs::remove_file(filename));
2299 let read_str = str::from_utf8(&read_mem).unwrap();
2300 assert_eq!(read_str, message);
2304 fn file_test_io_seek_and_tell_smoke_test() {
2305 let message = "ten-four";
2306 let mut read_mem = [0; 4];
2307 let set_cursor = 4 as u64;
2308 let tell_pos_pre_read;
2309 let tell_pos_post_read;
2310 let tmpdir = tmpdir();
2311 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
2313 let mut rw_stream = check!(File::create(filename));
2314 check!(rw_stream.write(message.as_bytes()));
2317 let mut read_stream = check!(File::open(filename));
2318 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
2319 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
2320 check!(read_stream.read(&mut read_mem));
2321 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
2323 check!(fs::remove_file(filename));
2324 let read_str = str::from_utf8(&read_mem).unwrap();
2325 assert_eq!(read_str, &message[4..8]);
2326 assert_eq!(tell_pos_pre_read, set_cursor);
2327 assert_eq!(tell_pos_post_read, message.len() as u64);
2331 fn file_test_io_seek_and_write() {
2332 let initial_msg = "food-is-yummy";
2333 let overwrite_msg = "-the-bar!!";
2334 let final_msg = "foo-the-bar!!";
2336 let mut read_mem = [0; 13];
2337 let tmpdir = tmpdir();
2338 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
2340 let mut rw_stream = check!(File::create(filename));
2341 check!(rw_stream.write(initial_msg.as_bytes()));
2342 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
2343 check!(rw_stream.write(overwrite_msg.as_bytes()));
2346 let mut read_stream = check!(File::open(filename));
2347 check!(read_stream.read(&mut read_mem));
2349 check!(fs::remove_file(filename));
2350 let read_str = str::from_utf8(&read_mem).unwrap();
2351 assert!(read_str == final_msg);
2355 fn file_test_io_seek_shakedown() {
2357 let initial_msg = "qwer-asdf-zxcv";
2358 let chunk_one: &str = "qwer";
2359 let chunk_two: &str = "asdf";
2360 let chunk_three: &str = "zxcv";
2361 let mut read_mem = [0; 4];
2362 let tmpdir = tmpdir();
2363 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2365 let mut rw_stream = check!(File::create(filename));
2366 check!(rw_stream.write(initial_msg.as_bytes()));
2369 let mut read_stream = check!(File::open(filename));
2371 check!(read_stream.seek(SeekFrom::End(-4)));
2372 check!(read_stream.read(&mut read_mem));
2373 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2375 check!(read_stream.seek(SeekFrom::Current(-9)));
2376 check!(read_stream.read(&mut read_mem));
2377 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2379 check!(read_stream.seek(SeekFrom::Start(0)));
2380 check!(read_stream.read(&mut read_mem));
2381 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2383 check!(fs::remove_file(filename));
2387 fn file_test_io_eof() {
2388 let tmpdir = tmpdir();
2389 let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2390 let mut buf = [0; 256];
2392 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2393 let mut rw = check!(oo.open(&filename));
2394 assert_eq!(check!(rw.read(&mut buf)), 0);
2395 assert_eq!(check!(rw.read(&mut buf)), 0);
2397 check!(fs::remove_file(&filename));
2402 fn file_test_io_read_write_at() {
2403 use crate::os::unix::fs::FileExt;
2405 let tmpdir = tmpdir();
2406 let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2407 let mut buf = [0; 256];
2408 let write1 = "asdf";
2409 let write2 = "qwer-";
2410 let write3 = "-zxcv";
2411 let content = "qwer-asdf-zxcv";
2413 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2414 let mut rw = check!(oo.open(&filename));
2415 assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2416 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2417 assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2418 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2419 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2420 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2421 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2422 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2423 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2424 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2425 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2426 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2427 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2428 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2429 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2430 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2431 assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2432 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2435 let mut read = check!(File::open(&filename));
2436 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2437 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2438 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2439 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2440 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2441 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2442 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2443 assert_eq!(check!(read.read(&mut buf)), write3.len());
2444 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2445 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2446 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2447 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2448 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2449 assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2450 assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2451 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2453 check!(fs::remove_file(&filename));
2458 fn set_get_unix_permissions() {
2459 use crate::os::unix::fs::PermissionsExt;
2461 let tmpdir = tmpdir();
2462 let filename = &tmpdir.join("set_get_unix_permissions");
2463 check!(fs::create_dir(filename));
2466 check!(fs::set_permissions(filename,
2467 fs::Permissions::from_mode(0)));
2468 let metadata0 = check!(fs::metadata(filename));
2469 assert_eq!(mask & metadata0.permissions().mode(), 0);
2471 check!(fs::set_permissions(filename,
2472 fs::Permissions::from_mode(0o1777)));
2473 let metadata1 = check!(fs::metadata(filename));
2474 assert_eq!(mask & metadata1.permissions().mode(), 0o1777);
2479 fn file_test_io_seek_read_write() {
2480 use crate::os::windows::fs::FileExt;
2482 let tmpdir = tmpdir();
2483 let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2484 let mut buf = [0; 256];
2485 let write1 = "asdf";
2486 let write2 = "qwer-";
2487 let write3 = "-zxcv";
2488 let content = "qwer-asdf-zxcv";
2490 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2491 let mut rw = check!(oo.open(&filename));
2492 assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2493 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2494 assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2495 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2496 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2497 assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2498 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2499 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2500 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2501 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2502 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2503 assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2504 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2505 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2506 assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2507 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2510 let mut read = check!(File::open(&filename));
2511 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2512 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2513 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2514 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2515 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2516 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2517 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2518 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2519 assert_eq!(check!(read.read(&mut buf)), write3.len());
2520 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2521 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2522 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2523 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2524 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2525 assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2526 assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2528 check!(fs::remove_file(&filename));
2532 fn file_test_stat_is_correct_on_is_file() {
2533 let tmpdir = tmpdir();
2534 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2536 let mut opts = OpenOptions::new();
2537 let mut fs = check!(opts.read(true).write(true)
2538 .create(true).open(filename));
2540 fs.write(msg.as_bytes()).unwrap();
2542 let fstat_res = check!(fs.metadata());
2543 assert!(fstat_res.is_file());
2545 let stat_res_fn = check!(fs::metadata(filename));
2546 assert!(stat_res_fn.is_file());
2547 let stat_res_meth = check!(filename.metadata());
2548 assert!(stat_res_meth.is_file());
2549 check!(fs::remove_file(filename));
2553 fn file_test_stat_is_correct_on_is_dir() {
2554 let tmpdir = tmpdir();
2555 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2556 check!(fs::create_dir(filename));
2557 let stat_res_fn = check!(fs::metadata(filename));
2558 assert!(stat_res_fn.is_dir());
2559 let stat_res_meth = check!(filename.metadata());
2560 assert!(stat_res_meth.is_dir());
2561 check!(fs::remove_dir(filename));
2565 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2566 let tmpdir = tmpdir();
2567 let dir = &tmpdir.join("fileinfo_false_on_dir");
2568 check!(fs::create_dir(dir));
2569 assert!(!dir.is_file());
2570 check!(fs::remove_dir(dir));
2574 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2575 let tmpdir = tmpdir();
2576 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2577 check!(check!(File::create(file)).write(b"foo"));
2578 assert!(file.exists());
2579 check!(fs::remove_file(file));
2580 assert!(!file.exists());
2584 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2585 let tmpdir = tmpdir();
2586 let dir = &tmpdir.join("before_and_after_dir");
2587 assert!(!dir.exists());
2588 check!(fs::create_dir(dir));
2589 assert!(dir.exists());
2590 assert!(dir.is_dir());
2591 check!(fs::remove_dir(dir));
2592 assert!(!dir.exists());
2596 fn file_test_directoryinfo_readdir() {
2597 let tmpdir = tmpdir();
2598 let dir = &tmpdir.join("di_readdir");
2599 check!(fs::create_dir(dir));
2602 let f = dir.join(&format!("{}.txt", n));
2603 let mut w = check!(File::create(&f));
2604 let msg_str = format!("{}{}", prefix, n.to_string());
2605 let msg = msg_str.as_bytes();
2606 check!(w.write(msg));
2608 let files = check!(fs::read_dir(dir));
2609 let mut mem = [0; 4];
2611 let f = f.unwrap().path();
2613 let n = f.file_stem().unwrap();
2614 check!(check!(File::open(&f)).read(&mut mem));
2615 let read_str = str::from_utf8(&mem).unwrap();
2616 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2617 assert_eq!(expected, read_str);
2619 check!(fs::remove_file(&f));
2621 check!(fs::remove_dir(dir));
2625 fn file_create_new_already_exists_error() {
2626 let tmpdir = tmpdir();
2627 let file = &tmpdir.join("file_create_new_error_exists");
2628 check!(fs::File::create(file));
2629 let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2630 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2634 fn mkdir_path_already_exists_error() {
2635 let tmpdir = tmpdir();
2636 let dir = &tmpdir.join("mkdir_error_twice");
2637 check!(fs::create_dir(dir));
2638 let e = fs::create_dir(dir).unwrap_err();
2639 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2643 fn recursive_mkdir() {
2644 let tmpdir = tmpdir();
2645 let dir = tmpdir.join("d1/d2");
2646 check!(fs::create_dir_all(&dir));
2647 assert!(dir.is_dir())
2651 fn recursive_mkdir_failure() {
2652 let tmpdir = tmpdir();
2653 let dir = tmpdir.join("d1");
2654 let file = dir.join("f1");
2656 check!(fs::create_dir_all(&dir));
2657 check!(File::create(&file));
2659 let result = fs::create_dir_all(&file);
2661 assert!(result.is_err());
2665 fn concurrent_recursive_mkdir() {
2668 let mut dir = dir.join("a");
2670 dir = dir.join("a");
2672 let mut join = vec!();
2674 let dir = dir.clone();
2675 join.push(thread::spawn(move || {
2676 check!(fs::create_dir_all(&dir));
2680 // No `Display` on result of `join()`
2681 join.drain(..).map(|join| join.join().unwrap()).count();
2686 fn recursive_mkdir_slash() {
2687 check!(fs::create_dir_all(Path::new("/")));
2691 fn recursive_mkdir_dot() {
2692 check!(fs::create_dir_all(Path::new(".")));
2696 fn recursive_mkdir_empty() {
2697 check!(fs::create_dir_all(Path::new("")));
2701 fn recursive_rmdir() {
2702 let tmpdir = tmpdir();
2703 let d1 = tmpdir.join("d1");
2704 let dt = d1.join("t");
2705 let dtt = dt.join("t");
2706 let d2 = tmpdir.join("d2");
2707 let canary = d2.join("do_not_delete");
2708 check!(fs::create_dir_all(&dtt));
2709 check!(fs::create_dir_all(&d2));
2710 check!(check!(File::create(&canary)).write(b"foo"));
2711 check!(symlink_junction(&d2, &dt.join("d2")));
2712 let _ = symlink_file(&canary, &d1.join("canary"));
2713 check!(fs::remove_dir_all(&d1));
2715 assert!(!d1.is_dir());
2716 assert!(canary.exists());
2720 fn recursive_rmdir_of_symlink() {
2721 // test we do not recursively delete a symlink but only dirs.
2722 let tmpdir = tmpdir();
2723 let link = tmpdir.join("d1");
2724 let dir = tmpdir.join("d2");
2725 let canary = dir.join("do_not_delete");
2726 check!(fs::create_dir_all(&dir));
2727 check!(check!(File::create(&canary)).write(b"foo"));
2728 check!(symlink_junction(&dir, &link));
2729 check!(fs::remove_dir_all(&link));
2731 assert!(!link.is_dir());
2732 assert!(canary.exists());
2736 // only Windows makes a distinction between file and directory symlinks.
2738 fn recursive_rmdir_of_file_symlink() {
2739 let tmpdir = tmpdir();
2740 if !got_symlink_permission(&tmpdir) { return };
2742 let f1 = tmpdir.join("f1");
2743 let f2 = tmpdir.join("f2");
2744 check!(check!(File::create(&f1)).write(b"foo"));
2745 check!(symlink_file(&f1, &f2));
2746 match fs::remove_dir_all(&f2) {
2747 Ok(..) => panic!("wanted a failure"),
2753 fn unicode_path_is_dir() {
2754 assert!(Path::new(".").is_dir());
2755 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2757 let tmpdir = tmpdir();
2759 let mut dirpath = tmpdir.path().to_path_buf();
2760 dirpath.push("test-가一ー你好");
2761 check!(fs::create_dir(&dirpath));
2762 assert!(dirpath.is_dir());
2764 let mut filepath = dirpath;
2765 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2766 check!(File::create(&filepath)); // ignore return; touch only
2767 assert!(!filepath.is_dir());
2768 assert!(filepath.exists());
2772 fn unicode_path_exists() {
2773 assert!(Path::new(".").exists());
2774 assert!(!Path::new("test/nonexistent-bogus-path").exists());
2776 let tmpdir = tmpdir();
2777 let unicode = tmpdir.path();
2778 let unicode = unicode.join("test-각丁ー再见");
2779 check!(fs::create_dir(&unicode));
2780 assert!(unicode.exists());
2781 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2785 fn copy_file_does_not_exist() {
2786 let from = Path::new("test/nonexistent-bogus-path");
2787 let to = Path::new("test/other-bogus-path");
2789 match fs::copy(&from, &to) {
2792 assert!(!from.exists());
2793 assert!(!to.exists());
2799 fn copy_src_does_not_exist() {
2800 let tmpdir = tmpdir();
2801 let from = Path::new("test/nonexistent-bogus-path");
2802 let to = tmpdir.join("out.txt");
2803 check!(check!(File::create(&to)).write(b"hello"));
2804 assert!(fs::copy(&from, &to).is_err());
2805 assert!(!from.exists());
2806 let mut v = Vec::new();
2807 check!(check!(File::open(&to)).read_to_end(&mut v));
2808 assert_eq!(v, b"hello");
2813 let tmpdir = tmpdir();
2814 let input = tmpdir.join("in.txt");
2815 let out = tmpdir.join("out.txt");
2817 check!(check!(File::create(&input)).write(b"hello"));
2818 check!(fs::copy(&input, &out));
2819 let mut v = Vec::new();
2820 check!(check!(File::open(&out)).read_to_end(&mut v));
2821 assert_eq!(v, b"hello");
2823 assert_eq!(check!(input.metadata()).permissions(),
2824 check!(out.metadata()).permissions());
2828 fn copy_file_dst_dir() {
2829 let tmpdir = tmpdir();
2830 let out = tmpdir.join("out");
2832 check!(File::create(&out));
2833 match fs::copy(&*out, tmpdir.path()) {
2834 Ok(..) => panic!(), Err(..) => {}
2839 fn copy_file_dst_exists() {
2840 let tmpdir = tmpdir();
2841 let input = tmpdir.join("in");
2842 let output = tmpdir.join("out");
2844 check!(check!(File::create(&input)).write("foo".as_bytes()));
2845 check!(check!(File::create(&output)).write("bar".as_bytes()));
2846 check!(fs::copy(&input, &output));
2848 let mut v = Vec::new();
2849 check!(check!(File::open(&output)).read_to_end(&mut v));
2850 assert_eq!(v, b"foo".to_vec());
2854 fn copy_file_src_dir() {
2855 let tmpdir = tmpdir();
2856 let out = tmpdir.join("out");
2858 match fs::copy(tmpdir.path(), &out) {
2859 Ok(..) => panic!(), Err(..) => {}
2861 assert!(!out.exists());
2865 fn copy_file_preserves_perm_bits() {
2866 let tmpdir = tmpdir();
2867 let input = tmpdir.join("in.txt");
2868 let out = tmpdir.join("out.txt");
2870 let attr = check!(check!(File::create(&input)).metadata());
2871 let mut p = attr.permissions();
2872 p.set_readonly(true);
2873 check!(fs::set_permissions(&input, p));
2874 check!(fs::copy(&input, &out));
2875 assert!(check!(out.metadata()).permissions().readonly());
2876 check!(fs::set_permissions(&input, attr.permissions()));
2877 check!(fs::set_permissions(&out, attr.permissions()));
2882 fn copy_file_preserves_streams() {
2884 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
2885 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 0);
2886 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
2887 let mut v = Vec::new();
2888 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
2889 assert_eq!(v, b"carrot".to_vec());
2893 fn copy_file_returns_metadata_len() {
2895 let in_path = tmp.join("in.txt");
2896 let out_path = tmp.join("out.txt");
2897 check!(check!(File::create(&in_path)).write(b"lettuce"));
2899 check!(check!(File::create(tmp.join("in.txt:bunny"))).write(b"carrot"));
2900 let copied_len = check!(fs::copy(&in_path, &out_path));
2901 assert_eq!(check!(out_path.metadata()).len(), copied_len);
2905 fn copy_file_follows_dst_symlink() {
2907 if !got_symlink_permission(&tmp) { return };
2909 let in_path = tmp.join("in.txt");
2910 let out_path = tmp.join("out.txt");
2911 let out_path_symlink = tmp.join("out_symlink.txt");
2913 check!(fs::write(&in_path, "foo"));
2914 check!(fs::write(&out_path, "bar"));
2915 check!(symlink_file(&out_path, &out_path_symlink));
2917 check!(fs::copy(&in_path, &out_path_symlink));
2919 assert!(check!(out_path_symlink.symlink_metadata()).file_type().is_symlink());
2920 assert_eq!(check!(fs::read(&out_path_symlink)), b"foo".to_vec());
2921 assert_eq!(check!(fs::read(&out_path)), b"foo".to_vec());
2925 fn symlinks_work() {
2926 let tmpdir = tmpdir();
2927 if !got_symlink_permission(&tmpdir) { return };
2929 let input = tmpdir.join("in.txt");
2930 let out = tmpdir.join("out.txt");
2932 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2933 check!(symlink_file(&input, &out));
2934 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
2935 assert_eq!(check!(fs::metadata(&out)).len(),
2936 check!(fs::metadata(&input)).len());
2937 let mut v = Vec::new();
2938 check!(check!(File::open(&out)).read_to_end(&mut v));
2939 assert_eq!(v, b"foobar".to_vec());
2943 fn symlink_noexist() {
2944 // Symlinks can point to things that don't exist
2945 let tmpdir = tmpdir();
2946 if !got_symlink_permission(&tmpdir) { return };
2948 // Use a relative path for testing. Symlinks get normalized by Windows,
2949 // so we may not get the same path back for absolute paths
2950 check!(symlink_file(&"foo", &tmpdir.join("bar")));
2951 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(),
2958 // directory symlink
2959 assert_eq!(check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
2962 assert_eq!(check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
2963 r"C:\Users\Default");
2964 // junction with special permissions
2965 assert_eq!(check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
2968 let tmpdir = tmpdir();
2969 let link = tmpdir.join("link");
2970 if !got_symlink_permission(&tmpdir) { return };
2971 check!(symlink_file(&"foo", &link));
2972 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
2976 fn readlink_not_symlink() {
2977 let tmpdir = tmpdir();
2978 match fs::read_link(tmpdir.path()) {
2979 Ok(..) => panic!("wanted a failure"),
2986 let tmpdir = tmpdir();
2987 let input = tmpdir.join("in.txt");
2988 let out = tmpdir.join("out.txt");
2990 check!(check!(File::create(&input)).write("foobar".as_bytes()));
2991 check!(fs::hard_link(&input, &out));
2992 assert_eq!(check!(fs::metadata(&out)).len(),
2993 check!(fs::metadata(&input)).len());
2994 assert_eq!(check!(fs::metadata(&out)).len(),
2995 check!(input.metadata()).len());
2996 let mut v = Vec::new();
2997 check!(check!(File::open(&out)).read_to_end(&mut v));
2998 assert_eq!(v, b"foobar".to_vec());
3000 // can't link to yourself
3001 match fs::hard_link(&input, &input) {
3002 Ok(..) => panic!("wanted a failure"),
3005 // can't link to something that doesn't exist
3006 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
3007 Ok(..) => panic!("wanted a failure"),
3014 let tmpdir = tmpdir();
3015 let file = tmpdir.join("in.txt");
3017 check!(File::create(&file));
3018 let attr = check!(fs::metadata(&file));
3019 assert!(!attr.permissions().readonly());
3020 let mut p = attr.permissions();
3021 p.set_readonly(true);
3022 check!(fs::set_permissions(&file, p.clone()));
3023 let attr = check!(fs::metadata(&file));
3024 assert!(attr.permissions().readonly());
3026 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
3027 Ok(..) => panic!("wanted an error"),
3031 p.set_readonly(false);
3032 check!(fs::set_permissions(&file, p));
3037 let tmpdir = tmpdir();
3038 let path = tmpdir.join("in.txt");
3040 let file = check!(File::create(&path));
3041 let attr = check!(fs::metadata(&path));
3042 assert!(!attr.permissions().readonly());
3043 let mut p = attr.permissions();
3044 p.set_readonly(true);
3045 check!(file.set_permissions(p.clone()));
3046 let attr = check!(fs::metadata(&path));
3047 assert!(attr.permissions().readonly());
3049 p.set_readonly(false);
3050 check!(file.set_permissions(p));
3054 fn sync_doesnt_kill_anything() {
3055 let tmpdir = tmpdir();
3056 let path = tmpdir.join("in.txt");
3058 let mut file = check!(File::create(&path));
3059 check!(file.sync_all());
3060 check!(file.sync_data());
3061 check!(file.write(b"foo"));
3062 check!(file.sync_all());
3063 check!(file.sync_data());
3067 fn truncate_works() {
3068 let tmpdir = tmpdir();
3069 let path = tmpdir.join("in.txt");
3071 let mut file = check!(File::create(&path));
3072 check!(file.write(b"foo"));
3073 check!(file.sync_all());
3075 // Do some simple things with truncation
3076 assert_eq!(check!(file.metadata()).len(), 3);
3077 check!(file.set_len(10));
3078 assert_eq!(check!(file.metadata()).len(), 10);
3079 check!(file.write(b"bar"));
3080 check!(file.sync_all());
3081 assert_eq!(check!(file.metadata()).len(), 10);
3083 let mut v = Vec::new();
3084 check!(check!(File::open(&path)).read_to_end(&mut v));
3085 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
3087 // Truncate to a smaller length, don't seek, and then write something.
3088 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
3089 // past the end of the file).
3090 check!(file.set_len(2));
3091 assert_eq!(check!(file.metadata()).len(), 2);
3092 check!(file.write(b"wut"));
3093 check!(file.sync_all());
3094 assert_eq!(check!(file.metadata()).len(), 9);
3095 let mut v = Vec::new();
3096 check!(check!(File::open(&path)).read_to_end(&mut v));
3097 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
3102 use crate::fs::OpenOptions as OO;
3103 fn c<T: Clone>(t: &T) -> T { t.clone() }
3105 let tmpdir = tmpdir();
3107 let mut r = OO::new(); r.read(true);
3108 let mut w = OO::new(); w.write(true);
3109 let mut rw = OO::new(); rw.read(true).write(true);
3110 let mut a = OO::new(); a.append(true);
3111 let mut ra = OO::new(); ra.read(true).append(true);
3114 let invalid_options = 87; // ERROR_INVALID_PARAMETER
3115 #[cfg(all(unix, not(target_os = "vxworks")))]
3116 let invalid_options = "Invalid argument";
3117 #[cfg(target_os = "vxworks")]
3118 let invalid_options = "invalid argument";
3120 // Test various combinations of creation modes and access modes.
3123 // creation mode | read | write | read-write | append | read-append |
3124 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
3125 // not set (open existing) | X | X | X | X | X |
3126 // create | | X | X | X | X |
3127 // truncate | | X | X | | |
3128 // create and truncate | | X | X | | |
3129 // create_new | | X | X | X | X |
3131 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
3134 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
3135 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
3136 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
3137 check!(c(&w).create(true).open(&tmpdir.join("a")));
3138 check!(c(&w).open(&tmpdir.join("a")));
3141 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
3142 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
3143 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
3144 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
3145 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
3148 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
3149 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
3150 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
3151 check!(c(&rw).create(true).open(&tmpdir.join("c")));
3152 check!(c(&rw).open(&tmpdir.join("c")));
3155 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
3156 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
3157 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
3158 check!(c(&a).create(true).open(&tmpdir.join("d")));
3159 check!(c(&a).open(&tmpdir.join("d")));
3162 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
3163 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
3164 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
3165 check!(c(&ra).create(true).open(&tmpdir.join("e")));
3166 check!(c(&ra).open(&tmpdir.join("e")));
3168 // Test opening a file without setting an access mode
3169 let mut blank = OO::new();
3170 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
3173 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
3175 // Test write fails for read-only
3176 check!(r.open(&tmpdir.join("h")));
3178 let mut f = check!(r.open(&tmpdir.join("h")));
3179 assert!(f.write("wut".as_bytes()).is_err());
3182 // Test write overwrites
3184 let mut f = check!(c(&w).open(&tmpdir.join("h")));
3185 check!(f.write("baz".as_bytes()));
3188 let mut f = check!(c(&r).open(&tmpdir.join("h")));
3189 let mut b = vec![0; 6];
3190 check!(f.read(&mut b));
3191 assert_eq!(b, "bazbar".as_bytes());
3194 // Test truncate works
3196 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
3197 check!(f.write("foo".as_bytes()));
3199 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3201 // Test append works
3202 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3204 let mut f = check!(c(&a).open(&tmpdir.join("h")));
3205 check!(f.write("bar".as_bytes()));
3207 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
3209 // Test .append(true) equals .write(true).append(true)
3211 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
3212 check!(f.write("baz".as_bytes()));
3214 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
3218 fn _assert_send_sync() {
3219 fn _assert_send_sync<T: Send + Sync>() {}
3220 _assert_send_sync::<OpenOptions>();
3225 let mut bytes = [0; 1024];
3226 StdRng::from_entropy().fill_bytes(&mut bytes);
3228 let tmpdir = tmpdir();
3230 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
3231 let mut v = Vec::new();
3232 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
3233 assert!(v == &bytes[..]);
3237 fn write_then_read() {
3238 let mut bytes = [0; 1024];
3239 StdRng::from_entropy().fill_bytes(&mut bytes);
3241 let tmpdir = tmpdir();
3243 check!(fs::write(&tmpdir.join("test"), &bytes[..]));
3244 let v = check!(fs::read(&tmpdir.join("test")));
3245 assert!(v == &bytes[..]);
3247 check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF]));
3248 error_contains!(fs::read_to_string(&tmpdir.join("not-utf8")),
3249 "stream did not contain valid UTF-8");
3252 check!(fs::write(&tmpdir.join("utf8"), s.as_bytes()));
3253 let string = check!(fs::read_to_string(&tmpdir.join("utf8")));
3254 assert_eq!(string, s);
3258 fn file_try_clone() {
3259 let tmpdir = tmpdir();
3261 let mut f1 = check!(OpenOptions::new()
3265 .open(&tmpdir.join("test")));
3266 let mut f2 = check!(f1.try_clone());
3268 check!(f1.write_all(b"hello world"));
3269 check!(f1.seek(SeekFrom::Start(2)));
3271 let mut buf = vec![];
3272 check!(f2.read_to_end(&mut buf));
3273 assert_eq!(buf, b"llo world");
3276 check!(f1.write_all(b"!"));
3280 #[cfg(not(windows))]
3281 fn unlink_readonly() {
3282 let tmpdir = tmpdir();
3283 let path = tmpdir.join("file");
3284 check!(File::create(&path));
3285 let mut perm = check!(fs::metadata(&path)).permissions();
3286 perm.set_readonly(true);
3287 check!(fs::set_permissions(&path, perm));
3288 check!(fs::remove_file(&path));
3292 fn mkdir_trailing_slash() {
3293 let tmpdir = tmpdir();
3294 let path = tmpdir.join("file");
3295 check!(fs::create_dir_all(&path.join("a/")));
3299 fn canonicalize_works_simple() {
3300 let tmpdir = tmpdir();
3301 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3302 let file = tmpdir.join("test");
3303 File::create(&file).unwrap();
3304 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3308 fn realpath_works() {
3309 let tmpdir = tmpdir();
3310 if !got_symlink_permission(&tmpdir) { return };
3312 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3313 let file = tmpdir.join("test");
3314 let dir = tmpdir.join("test2");
3315 let link = dir.join("link");
3316 let linkdir = tmpdir.join("test3");
3318 File::create(&file).unwrap();
3319 fs::create_dir(&dir).unwrap();
3320 symlink_file(&file, &link).unwrap();
3321 symlink_dir(&dir, &linkdir).unwrap();
3323 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
3325 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
3326 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3327 assert_eq!(fs::canonicalize(&link).unwrap(), file);
3328 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
3329 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
3333 fn realpath_works_tricky() {
3334 let tmpdir = tmpdir();
3335 if !got_symlink_permission(&tmpdir) { return };
3337 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3338 let a = tmpdir.join("a");
3339 let b = a.join("b");
3340 let c = b.join("c");
3341 let d = a.join("d");
3342 let e = d.join("e");
3343 let f = a.join("f");
3345 fs::create_dir_all(&b).unwrap();
3346 fs::create_dir_all(&d).unwrap();
3347 File::create(&f).unwrap();
3348 if cfg!(not(windows)) {
3349 symlink_file("../d/e", &c).unwrap();
3350 symlink_file("../f", &e).unwrap();
3353 symlink_file(r"..\d\e", &c).unwrap();
3354 symlink_file(r"..\f", &e).unwrap();
3357 assert_eq!(fs::canonicalize(&c).unwrap(), f);
3358 assert_eq!(fs::canonicalize(&e).unwrap(), f);
3362 fn dir_entry_methods() {
3363 let tmpdir = tmpdir();
3365 fs::create_dir_all(&tmpdir.join("a")).unwrap();
3366 File::create(&tmpdir.join("b")).unwrap();
3368 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
3369 let fname = file.file_name();
3370 match fname.to_str() {
3372 assert!(file.file_type().unwrap().is_dir());
3373 assert!(file.metadata().unwrap().is_dir());
3376 assert!(file.file_type().unwrap().is_file());
3377 assert!(file.metadata().unwrap().is_file());
3379 f => panic!("unknown file name: {:?}", f),
3385 fn dir_entry_debug() {
3386 let tmpdir = tmpdir();
3387 File::create(&tmpdir.join("b")).unwrap();
3388 let mut read_dir = tmpdir.path().read_dir().unwrap();
3389 let dir_entry = read_dir.next().unwrap().unwrap();
3390 let actual = format!("{:?}", dir_entry);
3391 let expected = format!("DirEntry({:?})", dir_entry.0.path());
3392 assert_eq!(actual, expected);
3396 fn read_dir_not_found() {
3397 let res = fs::read_dir("/path/that/does/not/exist");
3398 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
3402 fn create_dir_all_with_junctions() {
3403 let tmpdir = tmpdir();
3404 let target = tmpdir.join("target");
3406 let junction = tmpdir.join("junction");
3407 let b = junction.join("a/b");
3409 let link = tmpdir.join("link");
3410 let d = link.join("c/d");
3412 fs::create_dir(&target).unwrap();
3414 check!(symlink_junction(&target, &junction));
3415 check!(fs::create_dir_all(&b));
3416 // the junction itself is not a directory, but `is_dir()` on a Path
3418 assert!(junction.is_dir());
3419 assert!(b.exists());
3421 if !got_symlink_permission(&tmpdir) { return };
3422 check!(symlink_dir(&target, &link));
3423 check!(fs::create_dir_all(&d));
3424 assert!(link.is_dir());
3425 assert!(d.exists());
3429 fn metadata_access_times() {
3430 let tmpdir = tmpdir();
3432 let b = tmpdir.join("b");
3433 File::create(&b).unwrap();
3435 let a = check!(fs::metadata(&tmpdir.path()));
3436 let b = check!(fs::metadata(&b));
3438 assert_eq!(check!(a.accessed()), check!(a.accessed()));
3439 assert_eq!(check!(a.modified()), check!(a.modified()));
3440 assert_eq!(check!(b.accessed()), check!(b.modified()));
3442 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3443 check!(a.created());
3444 check!(b.created());