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")]
11 #![deny(unsafe_op_in_unsafe_fn)]
13 use crate::ffi::OsString;
15 use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
16 use crate::path::{Path, PathBuf};
17 use crate::sys::fs as fs_imp;
18 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
19 use crate::time::SystemTime;
21 /// A reference to an open file on the filesystem.
23 /// An instance of a `File` can be read and/or written depending on what options
24 /// it was opened with. Files also implement [`Seek`] to alter the logical cursor
25 /// that the file contains internally.
27 /// Files are automatically closed when they go out of scope. Errors detected
28 /// on closing are ignored by the implementation of `Drop`. Use the method
29 /// [`sync_all`] if these errors must be manually handled.
33 /// Creates a new file and write bytes to it (you can also use [`write`]):
36 /// use std::fs::File;
37 /// use std::io::prelude::*;
39 /// fn main() -> std::io::Result<()> {
40 /// let mut file = File::create("foo.txt")?;
41 /// file.write_all(b"Hello, world!")?;
46 /// Read the contents of a file into a [`String`] (you can also use [`read`]):
49 /// use std::fs::File;
50 /// use std::io::prelude::*;
52 /// fn main() -> std::io::Result<()> {
53 /// let mut file = File::open("foo.txt")?;
54 /// let mut contents = String::new();
55 /// file.read_to_string(&mut contents)?;
56 /// assert_eq!(contents, "Hello, world!");
61 /// It can be more efficient to read the contents of a file with a buffered
62 /// [`Read`]er. This can be accomplished with [`BufReader<R>`]:
65 /// use std::fs::File;
66 /// use std::io::BufReader;
67 /// use std::io::prelude::*;
69 /// fn main() -> std::io::Result<()> {
70 /// let file = File::open("foo.txt")?;
71 /// let mut buf_reader = BufReader::new(file);
72 /// let mut contents = String::new();
73 /// buf_reader.read_to_string(&mut contents)?;
74 /// assert_eq!(contents, "Hello, world!");
79 /// Note that, although read and write methods require a `&mut File`, because
80 /// of the interfaces for [`Read`] and [`Write`], the holder of a `&File` can
81 /// still modify the file, either through methods that take `&File` or by
82 /// retrieving the underlying OS object and modifying the file that way.
83 /// Additionally, many operating systems allow concurrent modification of files
84 /// by different processes. Avoid assuming that holding a `&File` means that the
85 /// file will not change.
87 /// [`Seek`]: ../io/trait.Seek.html
88 /// [`String`]: ../string/struct.String.html
89 /// [`Read`]: ../io/trait.Read.html
90 /// [`Write`]: ../io/trait.Write.html
91 /// [`BufReader<R>`]: ../io/struct.BufReader.html
92 /// [`sync_all`]: struct.File.html#method.sync_all
93 /// [`read`]: fn.read.html
94 /// [`write`]: fn.write.html
95 #[stable(feature = "rust1", since = "1.0.0")]
100 /// Metadata information about a file.
102 /// This structure is returned from the [`metadata`] or
103 /// [`symlink_metadata`] function or method and represents known
104 /// metadata about a file such as its permissions, size, modification
107 /// [`metadata`]: fn.metadata.html
108 /// [`symlink_metadata`]: fn.symlink_metadata.html
109 #[stable(feature = "rust1", since = "1.0.0")]
111 pub struct Metadata(fs_imp::FileAttr);
113 /// Iterator over the entries in a directory.
115 /// This iterator is returned from the [`read_dir`] function of this module and
116 /// will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. Through a [`DirEntry`]
117 /// information like the entry's path and possibly other metadata can be
120 /// The order in which this iterator returns entries is platform and filesystem
125 /// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
126 /// IO error during iteration.
128 /// [`read_dir`]: fn.read_dir.html
129 /// [`DirEntry`]: struct.DirEntry.html
130 /// [`io::Result`]: ../io/type.Result.html
131 /// [`Err`]: ../result/enum.Result.html#variant.Err
132 #[stable(feature = "rust1", since = "1.0.0")]
134 pub struct ReadDir(fs_imp::ReadDir);
136 /// Entries returned by the [`ReadDir`] iterator.
138 /// [`ReadDir`]: struct.ReadDir.html
140 /// An instance of `DirEntry` represents an entry inside of a directory on the
141 /// filesystem. Each entry can be inspected via methods to learn about the full
142 /// path or possibly other metadata through per-platform extension traits.
143 #[stable(feature = "rust1", since = "1.0.0")]
144 pub struct DirEntry(fs_imp::DirEntry);
146 /// Options and flags which can be used to configure how a file is opened.
148 /// This builder exposes the ability to configure how a [`File`] is opened and
149 /// what operations are permitted on the open file. The [`File::open`] and
150 /// [`File::create`] methods are aliases for commonly used options using this
153 /// [`File`]: struct.File.html
154 /// [`File::open`]: struct.File.html#method.open
155 /// [`File::create`]: struct.File.html#method.create
157 /// Generally speaking, when using `OpenOptions`, you'll first call [`new`],
158 /// then chain calls to methods to set each option, then call [`open`],
159 /// passing the path of the file you're trying to open. This will give you a
160 /// [`io::Result`][result] with a [`File`][file] inside that you can further
163 /// [`new`]: struct.OpenOptions.html#method.new
164 /// [`open`]: struct.OpenOptions.html#method.open
165 /// [result]: ../io/type.Result.html
166 /// [file]: struct.File.html
170 /// Opening a file to read:
173 /// use std::fs::OpenOptions;
175 /// let file = OpenOptions::new().read(true).open("foo.txt");
178 /// Opening a file for both reading and writing, as well as creating it if it
182 /// use std::fs::OpenOptions;
184 /// let file = OpenOptions::new()
188 /// .open("foo.txt");
190 #[derive(Clone, Debug)]
191 #[stable(feature = "rust1", since = "1.0.0")]
192 pub struct OpenOptions(fs_imp::OpenOptions);
194 /// Representation of the various permissions on a file.
196 /// This module only currently provides one bit of information, [`readonly`],
197 /// which is exposed on all currently supported platforms. Unix-specific
198 /// functionality, such as mode bits, is available through the
199 /// [`PermissionsExt`] trait.
201 /// [`readonly`]: struct.Permissions.html#method.readonly
202 /// [`PermissionsExt`]: ../os/unix/fs/trait.PermissionsExt.html
203 #[derive(Clone, PartialEq, Eq, Debug)]
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub struct Permissions(fs_imp::FilePermissions);
207 /// A structure representing a type of file with accessors for each file type.
208 /// It is returned by [`Metadata::file_type`] method.
210 /// [`Metadata::file_type`]: struct.Metadata.html#method.file_type
211 #[stable(feature = "file_type", since = "1.1.0")]
212 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
213 pub struct FileType(fs_imp::FileType);
215 /// A builder used to create directories in various manners.
217 /// This builder also supports platform-specific options.
218 #[stable(feature = "dir_builder", since = "1.6.0")]
220 pub struct DirBuilder {
221 inner: fs_imp::DirBuilder,
225 /// Indicates how large a buffer to pre-allocate before reading the entire file.
226 fn initial_buffer_size(file: &File) -> usize {
227 // Allocate one extra byte so the buffer doesn't need to grow before the
228 // final `read` call at the end of the file. Don't worry about `usize`
229 // overflow because reading will fail regardless in that case.
230 file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
233 /// Read the entire contents of a file into a bytes vector.
235 /// This is a convenience function for using [`File::open`] and [`read_to_end`]
236 /// with fewer imports and without an intermediate variable. It pre-allocates a
237 /// buffer based on the file size when available, so it is generally faster than
238 /// reading into a vector created with `Vec::new()`.
240 /// [`File::open`]: struct.File.html#method.open
241 /// [`read_to_end`]: ../io/trait.Read.html#method.read_to_end
245 /// This function will return an error if `path` does not already exist.
246 /// Other errors may also be returned according to [`OpenOptions::open`].
248 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
250 /// It will also return an error if it encounters while reading an error
251 /// of a kind other than [`ErrorKind::Interrupted`].
253 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
259 /// use std::net::SocketAddr;
261 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
262 /// let foo: SocketAddr = String::from_utf8_lossy(&fs::read("address.txt")?).parse()?;
266 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
267 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
268 fn inner(path: &Path) -> io::Result<Vec<u8>> {
269 let mut file = File::open(path)?;
270 let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
271 file.read_to_end(&mut bytes)?;
277 /// Read the entire contents of a file into a string.
279 /// This is a convenience function for using [`File::open`] and [`read_to_string`]
280 /// with fewer imports and without an intermediate variable. It pre-allocates a
281 /// buffer based on the file size when available, so it is generally faster than
282 /// reading into a string created with `String::new()`.
284 /// [`File::open`]: struct.File.html#method.open
285 /// [`read_to_string`]: ../io/trait.Read.html#method.read_to_string
289 /// This function will return an error if `path` does not already exist.
290 /// Other errors may also be returned according to [`OpenOptions::open`].
292 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
294 /// It will also return an error if it encounters while reading an error
295 /// of a kind other than [`ErrorKind::Interrupted`],
296 /// or if the contents of the file are not valid UTF-8.
298 /// [`ErrorKind::Interrupted`]: ../../std/io/enum.ErrorKind.html#variant.Interrupted
304 /// use std::net::SocketAddr;
306 /// fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
307 /// let foo: SocketAddr = fs::read_to_string("address.txt")?.parse()?;
311 #[stable(feature = "fs_read_write", since = "1.26.0")]
312 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
313 fn inner(path: &Path) -> io::Result<String> {
314 let mut file = File::open(path)?;
315 let mut string = String::with_capacity(initial_buffer_size(&file));
316 file.read_to_string(&mut string)?;
322 /// Write a slice as the entire contents of a file.
324 /// This function will create a file if it does not exist,
325 /// and will entirely replace its contents if it does.
327 /// This is a convenience function for using [`File::create`] and [`write_all`]
328 /// with fewer imports.
330 /// [`File::create`]: struct.File.html#method.create
331 /// [`write_all`]: ../io/trait.Write.html#method.write_all
338 /// fn main() -> std::io::Result<()> {
339 /// fs::write("foo.txt", b"Lorem ipsum")?;
340 /// fs::write("bar.txt", "dolor sit")?;
344 #[stable(feature = "fs_read_write_bytes", since = "1.26.0")]
345 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
346 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
347 File::create(path)?.write_all(contents)
349 inner(path.as_ref(), contents.as_ref())
353 /// Attempts to open a file in read-only mode.
355 /// See the [`OpenOptions::open`] method for more details.
359 /// This function will return an error if `path` does not already exist.
360 /// Other errors may also be returned according to [`OpenOptions::open`].
362 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
367 /// use std::fs::File;
369 /// fn main() -> std::io::Result<()> {
370 /// let mut f = File::open("foo.txt")?;
374 #[stable(feature = "rust1", since = "1.0.0")]
375 pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
376 OpenOptions::new().read(true).open(path.as_ref())
379 /// Opens a file in write-only mode.
381 /// This function will create a file if it does not exist,
382 /// and will truncate it if it does.
384 /// See the [`OpenOptions::open`] function for more details.
386 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
391 /// use std::fs::File;
393 /// fn main() -> std::io::Result<()> {
394 /// let mut f = File::create("foo.txt")?;
398 #[stable(feature = "rust1", since = "1.0.0")]
399 pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
400 OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
403 /// Returns a new OpenOptions object.
405 /// This function returns a new OpenOptions object that you can use to
406 /// open or create a file with specific options if `open()` or `create()`
407 /// are not appropriate.
409 /// It is equivalent to `OpenOptions::new()` but allows you to write more
410 /// readable code. Instead of `OpenOptions::new().read(true).open("foo.txt")`
411 /// you can write `File::with_options().read(true).open("foo.txt")`. This
412 /// also avoids the need to import `OpenOptions`.
414 /// See the [`OpenOptions::new`] function for more details.
416 /// [`OpenOptions::new`]: struct.OpenOptions.html#method.new
421 /// #![feature(with_options)]
422 /// use std::fs::File;
424 /// fn main() -> std::io::Result<()> {
425 /// let mut f = File::with_options().read(true).open("foo.txt")?;
429 #[unstable(feature = "with_options", issue = "65439")]
430 pub fn with_options() -> OpenOptions {
434 /// Attempts to sync all OS-internal metadata to disk.
436 /// This function will attempt to ensure that all in-memory data reaches the
437 /// filesystem before returning.
439 /// This can be used to handle errors that would otherwise only be caught
440 /// when the `File` is closed. Dropping a file will ignore errors in
441 /// synchronizing this in-memory data.
446 /// use std::fs::File;
447 /// use std::io::prelude::*;
449 /// fn main() -> std::io::Result<()> {
450 /// let mut f = File::create("foo.txt")?;
451 /// f.write_all(b"Hello, world!")?;
457 #[stable(feature = "rust1", since = "1.0.0")]
458 pub fn sync_all(&self) -> io::Result<()> {
462 /// This function is similar to [`sync_all`], except that it may not
463 /// synchronize file metadata to the filesystem.
465 /// This is intended for use cases that must synchronize content, but don't
466 /// need the metadata on disk. The goal of this method is to reduce disk
469 /// Note that some platforms may simply implement this in terms of
472 /// [`sync_all`]: struct.File.html#method.sync_all
477 /// use std::fs::File;
478 /// use std::io::prelude::*;
480 /// fn main() -> std::io::Result<()> {
481 /// let mut f = File::create("foo.txt")?;
482 /// f.write_all(b"Hello, world!")?;
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub fn sync_data(&self) -> io::Result<()> {
490 self.inner.datasync()
493 /// Truncates or extends the underlying file, updating the size of
494 /// this file to become `size`.
496 /// If the `size` is less than the current file's size, then the file will
497 /// be shrunk. If it is greater than the current file's size, then the file
498 /// will be extended to `size` and have all of the intermediate data filled
501 /// The file's cursor isn't changed. In particular, if the cursor was at the
502 /// end and the file is shrunk using this operation, the cursor will now be
507 /// This function will return an error if the file is not opened for writing.
508 /// Also, std::io::ErrorKind::InvalidInput will be returned if the desired
509 /// length would cause an overflow due to the implementation specifics.
514 /// use std::fs::File;
516 /// fn main() -> std::io::Result<()> {
517 /// let mut f = File::create("foo.txt")?;
523 /// Note that this method alters the content of the underlying file, even
524 /// though it takes `&self` rather than `&mut self`.
525 #[stable(feature = "rust1", since = "1.0.0")]
526 pub fn set_len(&self, size: u64) -> io::Result<()> {
527 self.inner.truncate(size)
530 /// Queries metadata about the underlying file.
535 /// use std::fs::File;
537 /// fn main() -> std::io::Result<()> {
538 /// let mut f = File::open("foo.txt")?;
539 /// let metadata = f.metadata()?;
543 #[stable(feature = "rust1", since = "1.0.0")]
544 pub fn metadata(&self) -> io::Result<Metadata> {
545 self.inner.file_attr().map(Metadata)
548 /// Creates a new `File` instance that shares the same underlying file handle
549 /// as the existing `File` instance. Reads, writes, and seeks will affect
550 /// both `File` instances simultaneously.
554 /// Creates two handles for a file named `foo.txt`:
557 /// use std::fs::File;
559 /// fn main() -> std::io::Result<()> {
560 /// let mut file = File::open("foo.txt")?;
561 /// let file_copy = file.try_clone()?;
566 /// Assuming there’s a file named `foo.txt` with contents `abcdef\n`, create
567 /// two handles, seek one of them, and read the remaining bytes from the
571 /// use std::fs::File;
572 /// use std::io::SeekFrom;
573 /// use std::io::prelude::*;
575 /// fn main() -> std::io::Result<()> {
576 /// let mut file = File::open("foo.txt")?;
577 /// let mut file_copy = file.try_clone()?;
579 /// file.seek(SeekFrom::Start(3))?;
581 /// let mut contents = vec![];
582 /// file_copy.read_to_end(&mut contents)?;
583 /// assert_eq!(contents, b"def\n");
587 #[stable(feature = "file_try_clone", since = "1.9.0")]
588 pub fn try_clone(&self) -> io::Result<File> {
589 Ok(File { inner: self.inner.duplicate()? })
592 /// Changes the permissions on the underlying file.
594 /// # Platform-specific behavior
596 /// This function currently corresponds to the `fchmod` function on Unix and
597 /// the `SetFileInformationByHandle` function on Windows. Note that, this
598 /// [may change in the future][changes].
600 /// [changes]: ../io/index.html#platform-specific-behavior
604 /// This function will return an error if the user lacks permission change
605 /// attributes on the underlying file. It may also return an error in other
606 /// os-specific unspecified cases.
611 /// fn main() -> std::io::Result<()> {
612 /// use std::fs::File;
614 /// let file = File::open("foo.txt")?;
615 /// let mut perms = file.metadata()?.permissions();
616 /// perms.set_readonly(true);
617 /// file.set_permissions(perms)?;
622 /// Note that this method alters the permissions of the underlying file,
623 /// even though it takes `&self` rather than `&mut self`.
624 #[stable(feature = "set_permissions_atomic", since = "1.16.0")]
625 pub fn set_permissions(&self, perm: Permissions) -> io::Result<()> {
626 self.inner.set_permissions(perm.0)
630 impl AsInner<fs_imp::File> for File {
631 fn as_inner(&self) -> &fs_imp::File {
635 impl FromInner<fs_imp::File> for File {
636 fn from_inner(f: fs_imp::File) -> File {
640 impl IntoInner<fs_imp::File> for File {
641 fn into_inner(self) -> fs_imp::File {
646 #[stable(feature = "rust1", since = "1.0.0")]
647 impl fmt::Debug for File {
648 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
653 #[stable(feature = "rust1", since = "1.0.0")]
655 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
659 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
660 self.inner.read_vectored(bufs)
664 fn is_read_vectored(&self) -> bool {
665 self.inner.is_read_vectored()
669 unsafe fn initializer(&self) -> Initializer {
670 // SAFETY: Read is guaranteed to work on uninitialized memory
671 unsafe { Initializer::nop() }
674 #[stable(feature = "rust1", since = "1.0.0")]
675 impl Write for File {
676 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
677 self.inner.write(buf)
680 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
681 self.inner.write_vectored(bufs)
685 fn is_write_vectored(&self) -> bool {
686 self.inner.is_write_vectored()
689 fn flush(&mut self) -> io::Result<()> {
693 #[stable(feature = "rust1", since = "1.0.0")]
695 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
699 #[stable(feature = "rust1", since = "1.0.0")]
700 impl Read for &File {
701 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
705 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
706 self.inner.read_vectored(bufs)
710 fn is_read_vectored(&self) -> bool {
711 self.inner.is_read_vectored()
715 unsafe fn initializer(&self) -> Initializer {
716 // SAFETY: Read is guaranteed to work on uninitialized memory
717 unsafe { Initializer::nop() }
720 #[stable(feature = "rust1", since = "1.0.0")]
721 impl Write for &File {
722 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
723 self.inner.write(buf)
726 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
727 self.inner.write_vectored(bufs)
731 fn is_write_vectored(&self) -> bool {
732 self.inner.is_write_vectored()
735 fn flush(&mut self) -> io::Result<()> {
739 #[stable(feature = "rust1", since = "1.0.0")]
740 impl Seek for &File {
741 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
747 /// Creates a blank new set of options ready for configuration.
749 /// All options are initially set to `false`.
754 /// use std::fs::OpenOptions;
756 /// let mut options = OpenOptions::new();
757 /// let file = options.read(true).open("foo.txt");
759 #[stable(feature = "rust1", since = "1.0.0")]
760 pub fn new() -> Self {
761 OpenOptions(fs_imp::OpenOptions::new())
764 /// Sets the option for read access.
766 /// This option, when true, will indicate that the file should be
767 /// `read`-able if opened.
772 /// use std::fs::OpenOptions;
774 /// let file = OpenOptions::new().read(true).open("foo.txt");
776 #[stable(feature = "rust1", since = "1.0.0")]
777 pub fn read(&mut self, read: bool) -> &mut Self {
782 /// Sets the option for write access.
784 /// This option, when true, will indicate that the file should be
785 /// `write`-able if opened.
787 /// If the file already exists, any write calls on it will overwrite its
788 /// contents, without truncating it.
793 /// use std::fs::OpenOptions;
795 /// let file = OpenOptions::new().write(true).open("foo.txt");
797 #[stable(feature = "rust1", since = "1.0.0")]
798 pub fn write(&mut self, write: bool) -> &mut Self {
803 /// Sets the option for the append mode.
805 /// This option, when true, means that writes will append to a file instead
806 /// of overwriting previous contents.
807 /// Note that setting `.write(true).append(true)` has the same effect as
808 /// setting only `.append(true)`.
810 /// For most filesystems, the operating system guarantees that all writes are
811 /// atomic: no writes get mangled because another process writes at the same
814 /// One maybe obvious note when using append-mode: make sure that all data
815 /// that belongs together is written to the file in one operation. This
816 /// can be done by concatenating strings before passing them to [`write()`],
817 /// or using a buffered writer (with a buffer of adequate size),
818 /// and calling [`flush()`] when the message is complete.
820 /// If a file is opened with both read and append access, beware that after
821 /// opening, and after every write, the position for reading may be set at the
822 /// end of the file. So, before writing, save the current position (using
823 /// [`seek`]`(`[`SeekFrom`]`::`[`Current`]`(0))`), and restore it before the next read.
827 /// This function doesn't create the file if it doesn't exist. Use the [`create`]
830 /// [`write()`]: ../../std/fs/struct.File.html#method.write
831 /// [`flush()`]: ../../std/fs/struct.File.html#method.flush
832 /// [`seek`]: ../../std/fs/struct.File.html#method.seek
833 /// [`SeekFrom`]: ../../std/io/enum.SeekFrom.html
834 /// [`Current`]: ../../std/io/enum.SeekFrom.html#variant.Current
835 /// [`create`]: #method.create
840 /// use std::fs::OpenOptions;
842 /// let file = OpenOptions::new().append(true).open("foo.txt");
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub fn append(&mut self, append: bool) -> &mut Self {
846 self.0.append(append);
850 /// Sets the option for truncating a previous file.
852 /// If a file is successfully opened with this option set it will truncate
853 /// the file to 0 length if it already exists.
855 /// The file must be opened with write access for truncate to work.
860 /// use std::fs::OpenOptions;
862 /// let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");
864 #[stable(feature = "rust1", since = "1.0.0")]
865 pub fn truncate(&mut self, truncate: bool) -> &mut Self {
866 self.0.truncate(truncate);
870 /// Sets the option to create a new file, or open it if it already exists.
872 /// In order for the file to be created, [`write`] or [`append`] access must
875 /// [`write`]: #method.write
876 /// [`append`]: #method.append
881 /// use std::fs::OpenOptions;
883 /// let file = OpenOptions::new().write(true).create(true).open("foo.txt");
885 #[stable(feature = "rust1", since = "1.0.0")]
886 pub fn create(&mut self, create: bool) -> &mut Self {
887 self.0.create(create);
891 /// Sets the option to create a new file, failing if it already exists.
893 /// No file is allowed to exist at the target location, also no (dangling) symlink. In this
894 /// way, if the call succeeds, the file returned is guaranteed to be new.
896 /// This option is useful because it is atomic. Otherwise between checking
897 /// whether a file exists and creating a new one, the file may have been
898 /// created by another process (a TOCTOU race condition / attack).
900 /// If `.create_new(true)` is set, [`.create()`] and [`.truncate()`] are
903 /// The file must be opened with write or append access in order to create
906 /// [`.create()`]: #method.create
907 /// [`.truncate()`]: #method.truncate
912 /// use std::fs::OpenOptions;
914 /// let file = OpenOptions::new().write(true)
915 /// .create_new(true)
916 /// .open("foo.txt");
918 #[stable(feature = "expand_open_options2", since = "1.9.0")]
919 pub fn create_new(&mut self, create_new: bool) -> &mut Self {
920 self.0.create_new(create_new);
924 /// Opens a file at `path` with the options specified by `self`.
928 /// This function will return an error under a number of different
929 /// circumstances. Some of these error conditions are listed here, together
930 /// with their [`ErrorKind`]. The mapping to [`ErrorKind`]s is not part of
931 /// the compatibility contract of the function, especially the `Other` kind
932 /// might change to more specific kinds in the future.
934 /// * [`NotFound`]: The specified file does not exist and neither `create`
935 /// or `create_new` is set.
936 /// * [`NotFound`]: One of the directory components of the file path does
938 /// * [`PermissionDenied`]: The user lacks permission to get the specified
939 /// access rights for the file.
940 /// * [`PermissionDenied`]: The user lacks permission to open one of the
941 /// directory components of the specified path.
942 /// * [`AlreadyExists`]: `create_new` was specified and the file already
944 /// * [`InvalidInput`]: Invalid combinations of open options (truncate
945 /// without write access, no access mode set, etc.).
946 /// * [`Other`]: One of the directory components of the specified file path
947 /// was not, in fact, a directory.
948 /// * [`Other`]: Filesystem-level errors: full disk, write permission
949 /// requested on a read-only file system, exceeded disk quota, too many
950 /// open files, too long filename, too many symbolic links in the
951 /// specified path (Unix-like systems only), etc.
956 /// use std::fs::OpenOptions;
958 /// let file = OpenOptions::new().read(true).open("foo.txt");
961 /// [`ErrorKind`]: ../io/enum.ErrorKind.html
962 /// [`AlreadyExists`]: ../io/enum.ErrorKind.html#variant.AlreadyExists
963 /// [`InvalidInput`]: ../io/enum.ErrorKind.html#variant.InvalidInput
964 /// [`NotFound`]: ../io/enum.ErrorKind.html#variant.NotFound
965 /// [`Other`]: ../io/enum.ErrorKind.html#variant.Other
966 /// [`PermissionDenied`]: ../io/enum.ErrorKind.html#variant.PermissionDenied
967 #[stable(feature = "rust1", since = "1.0.0")]
968 pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
969 self._open(path.as_ref())
972 fn _open(&self, path: &Path) -> io::Result<File> {
973 fs_imp::File::open(path, &self.0).map(|inner| File { inner })
977 impl AsInner<fs_imp::OpenOptions> for OpenOptions {
978 fn as_inner(&self) -> &fs_imp::OpenOptions {
983 impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
984 fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions {
990 /// Returns the file type for this metadata.
995 /// fn main() -> std::io::Result<()> {
998 /// let metadata = fs::metadata("foo.txt")?;
1000 /// println!("{:?}", metadata.file_type());
1004 #[stable(feature = "file_type", since = "1.1.0")]
1005 pub fn file_type(&self) -> FileType {
1006 FileType(self.0.file_type())
1009 /// Returns `true` if this metadata is for a directory. The
1010 /// result is mutually exclusive to the result of
1011 /// [`is_file`], and will be false for symlink metadata
1012 /// obtained from [`symlink_metadata`].
1014 /// [`is_file`]: struct.Metadata.html#method.is_file
1015 /// [`symlink_metadata`]: fn.symlink_metadata.html
1020 /// fn main() -> std::io::Result<()> {
1023 /// let metadata = fs::metadata("foo.txt")?;
1025 /// assert!(!metadata.is_dir());
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 pub fn is_dir(&self) -> bool {
1031 self.file_type().is_dir()
1034 /// Returns `true` if this metadata is for a regular file. The
1035 /// result is mutually exclusive to the result of
1036 /// [`is_dir`], and will be false for symlink metadata
1037 /// obtained from [`symlink_metadata`].
1039 /// When the goal is simply to read from (or write to) the source, the most
1040 /// reliable way to test the source can be read (or written to) is to open
1041 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1042 /// a Unix-like system for example. See [`File::open`] or
1043 /// [`OpenOptions::open`] for more information.
1045 /// [`is_dir`]: struct.Metadata.html#method.is_dir
1046 /// [`symlink_metadata`]: fn.symlink_metadata.html
1047 /// [`File::open`]: struct.File.html#method.open
1048 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
1055 /// fn main() -> std::io::Result<()> {
1056 /// let metadata = fs::metadata("foo.txt")?;
1058 /// assert!(metadata.is_file());
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 pub fn is_file(&self) -> bool {
1064 self.file_type().is_file()
1067 /// Returns the size of the file, in bytes, this metadata is for.
1074 /// fn main() -> std::io::Result<()> {
1075 /// let metadata = fs::metadata("foo.txt")?;
1077 /// assert_eq!(0, metadata.len());
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 pub fn len(&self) -> u64 {
1086 /// Returns the permissions of the file this metadata is for.
1093 /// fn main() -> std::io::Result<()> {
1094 /// let metadata = fs::metadata("foo.txt")?;
1096 /// assert!(!metadata.permissions().readonly());
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 pub fn permissions(&self) -> Permissions {
1102 Permissions(self.0.perm())
1105 /// Returns the last modification time listed in this metadata.
1107 /// The returned value corresponds to the `mtime` field of `stat` on Unix
1108 /// platforms and the `ftLastWriteTime` field on Windows platforms.
1112 /// This field may not be available on all platforms, and will return an
1113 /// `Err` on platforms where it is not available.
1120 /// fn main() -> std::io::Result<()> {
1121 /// let metadata = fs::metadata("foo.txt")?;
1123 /// if let Ok(time) = metadata.modified() {
1124 /// println!("{:?}", time);
1126 /// println!("Not supported on this platform");
1131 #[stable(feature = "fs_time", since = "1.10.0")]
1132 pub fn modified(&self) -> io::Result<SystemTime> {
1133 self.0.modified().map(FromInner::from_inner)
1136 /// Returns the last access time of this metadata.
1138 /// The returned value corresponds to the `atime` field of `stat` on Unix
1139 /// platforms and the `ftLastAccessTime` field on Windows platforms.
1141 /// Note that not all platforms will keep this field update in a file's
1142 /// metadata, for example Windows has an option to disable updating this
1143 /// time when files are accessed and Linux similarly has `noatime`.
1147 /// This field may not be available on all platforms, and will return an
1148 /// `Err` on platforms where it is not available.
1155 /// fn main() -> std::io::Result<()> {
1156 /// let metadata = fs::metadata("foo.txt")?;
1158 /// if let Ok(time) = metadata.accessed() {
1159 /// println!("{:?}", time);
1161 /// println!("Not supported on this platform");
1166 #[stable(feature = "fs_time", since = "1.10.0")]
1167 pub fn accessed(&self) -> io::Result<SystemTime> {
1168 self.0.accessed().map(FromInner::from_inner)
1171 /// Returns the creation time listed in this metadata.
1173 /// The returned value corresponds to the `btime` field of `statx` on
1174 /// Linux kernel starting from to 4.11, the `birthtime` field of `stat` on other
1175 /// Unix platforms, and the `ftCreationTime` field on Windows platforms.
1179 /// This field may not be available on all platforms, and will return an
1180 /// `Err` on platforms or filesystems where it is not available.
1187 /// fn main() -> std::io::Result<()> {
1188 /// let metadata = fs::metadata("foo.txt")?;
1190 /// if let Ok(time) = metadata.created() {
1191 /// println!("{:?}", time);
1193 /// println!("Not supported on this platform or filesystem");
1198 #[stable(feature = "fs_time", since = "1.10.0")]
1199 pub fn created(&self) -> io::Result<SystemTime> {
1200 self.0.created().map(FromInner::from_inner)
1204 #[stable(feature = "std_debug", since = "1.16.0")]
1205 impl fmt::Debug for Metadata {
1206 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1207 f.debug_struct("Metadata")
1208 .field("file_type", &self.file_type())
1209 .field("is_dir", &self.is_dir())
1210 .field("is_file", &self.is_file())
1211 .field("permissions", &self.permissions())
1212 .field("modified", &self.modified())
1213 .field("accessed", &self.accessed())
1214 .field("created", &self.created())
1219 impl AsInner<fs_imp::FileAttr> for Metadata {
1220 fn as_inner(&self) -> &fs_imp::FileAttr {
1225 impl FromInner<fs_imp::FileAttr> for Metadata {
1226 fn from_inner(attr: fs_imp::FileAttr) -> Metadata {
1232 /// Returns `true` if these permissions describe a readonly (unwritable) file.
1237 /// use std::fs::File;
1239 /// fn main() -> std::io::Result<()> {
1240 /// let mut f = File::create("foo.txt")?;
1241 /// let metadata = f.metadata()?;
1243 /// assert_eq!(false, metadata.permissions().readonly());
1247 #[stable(feature = "rust1", since = "1.0.0")]
1248 pub fn readonly(&self) -> bool {
1252 /// Modifies the readonly flag for this set of permissions. If the
1253 /// `readonly` argument is `true`, using the resulting `Permission` will
1254 /// update file permissions to forbid writing. Conversely, if it's `false`,
1255 /// using the resulting `Permission` will update file permissions to allow
1258 /// This operation does **not** modify the filesystem. To modify the
1259 /// filesystem use the [`fs::set_permissions`] function.
1261 /// [`fs::set_permissions`]: fn.set_permissions.html
1266 /// use std::fs::File;
1268 /// fn main() -> std::io::Result<()> {
1269 /// let f = File::create("foo.txt")?;
1270 /// let metadata = f.metadata()?;
1271 /// let mut permissions = metadata.permissions();
1273 /// permissions.set_readonly(true);
1275 /// // filesystem doesn't change
1276 /// assert_eq!(false, metadata.permissions().readonly());
1278 /// // just this particular `permissions`.
1279 /// assert_eq!(true, permissions.readonly());
1283 #[stable(feature = "rust1", since = "1.0.0")]
1284 pub fn set_readonly(&mut self, readonly: bool) {
1285 self.0.set_readonly(readonly)
1290 /// Tests whether this file type represents a directory. The
1291 /// result is mutually exclusive to the results of
1292 /// [`is_file`] and [`is_symlink`]; only zero or one of these
1295 /// [`is_file`]: struct.FileType.html#method.is_file
1296 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1301 /// fn main() -> std::io::Result<()> {
1304 /// let metadata = fs::metadata("foo.txt")?;
1305 /// let file_type = metadata.file_type();
1307 /// assert_eq!(file_type.is_dir(), false);
1311 #[stable(feature = "file_type", since = "1.1.0")]
1312 pub fn is_dir(&self) -> bool {
1316 /// Tests whether this file type represents a regular file.
1317 /// The result is mutually exclusive to the results of
1318 /// [`is_dir`] and [`is_symlink`]; only zero or one of these
1321 /// When the goal is simply to read from (or write to) the source, the most
1322 /// reliable way to test the source can be read (or written to) is to open
1323 /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1324 /// a Unix-like system for example. See [`File::open`] or
1325 /// [`OpenOptions::open`] for more information.
1327 /// [`is_dir`]: struct.FileType.html#method.is_dir
1328 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1329 /// [`File::open`]: struct.File.html#method.open
1330 /// [`OpenOptions::open`]: struct.OpenOptions.html#method.open
1335 /// fn main() -> std::io::Result<()> {
1338 /// let metadata = fs::metadata("foo.txt")?;
1339 /// let file_type = metadata.file_type();
1341 /// assert_eq!(file_type.is_file(), true);
1345 #[stable(feature = "file_type", since = "1.1.0")]
1346 pub fn is_file(&self) -> bool {
1350 /// Tests whether this file type represents a symbolic link.
1351 /// The result is mutually exclusive to the results of
1352 /// [`is_dir`] and [`is_file`]; only zero or one of these
1355 /// The underlying [`Metadata`] struct needs to be retrieved
1356 /// with the [`fs::symlink_metadata`] function and not the
1357 /// [`fs::metadata`] function. The [`fs::metadata`] function
1358 /// follows symbolic links, so [`is_symlink`] would always
1359 /// return `false` for the target file.
1361 /// [`Metadata`]: struct.Metadata.html
1362 /// [`fs::metadata`]: fn.metadata.html
1363 /// [`fs::symlink_metadata`]: fn.symlink_metadata.html
1364 /// [`is_dir`]: struct.FileType.html#method.is_dir
1365 /// [`is_file`]: struct.FileType.html#method.is_file
1366 /// [`is_symlink`]: struct.FileType.html#method.is_symlink
1373 /// fn main() -> std::io::Result<()> {
1374 /// let metadata = fs::symlink_metadata("foo.txt")?;
1375 /// let file_type = metadata.file_type();
1377 /// assert_eq!(file_type.is_symlink(), false);
1381 #[stable(feature = "file_type", since = "1.1.0")]
1382 pub fn is_symlink(&self) -> bool {
1387 impl AsInner<fs_imp::FileType> for FileType {
1388 fn as_inner(&self) -> &fs_imp::FileType {
1393 impl FromInner<fs_imp::FilePermissions> for Permissions {
1394 fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
1399 impl AsInner<fs_imp::FilePermissions> for Permissions {
1400 fn as_inner(&self) -> &fs_imp::FilePermissions {
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 impl Iterator for ReadDir {
1407 type Item = io::Result<DirEntry>;
1409 fn next(&mut self) -> Option<io::Result<DirEntry>> {
1410 self.0.next().map(|entry| entry.map(DirEntry))
1415 /// Returns the full path to the file that this entry represents.
1417 /// The full path is created by joining the original path to `read_dir`
1418 /// with the filename of this entry.
1425 /// fn main() -> std::io::Result<()> {
1426 /// for entry in fs::read_dir(".")? {
1427 /// let dir = entry?;
1428 /// println!("{:?}", dir.path());
1434 /// This prints output like:
1437 /// "./whatever.txt"
1439 /// "./hello_world.rs"
1442 /// The exact text, of course, depends on what files you have in `.`.
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 pub fn path(&self) -> PathBuf {
1448 /// Returns the metadata for the file that this entry points at.
1450 /// This function will not traverse symlinks if this entry points at a
1451 /// symlink. To traverse symlinks use [`fs::metadata`] or [`fs::File::metadata`].
1453 /// [`fs::metadata`]: fn.metadata.html
1454 /// [`fs::File::metadata`]: struct.File.html#method.metadata
1456 /// # Platform-specific behavior
1458 /// On Windows this function is cheap to call (no extra system calls
1459 /// needed), but on Unix platforms this function is the equivalent of
1460 /// calling `symlink_metadata` on the path.
1467 /// if let Ok(entries) = fs::read_dir(".") {
1468 /// for entry in entries {
1469 /// if let Ok(entry) = entry {
1470 /// // Here, `entry` is a `DirEntry`.
1471 /// if let Ok(metadata) = entry.metadata() {
1472 /// // Now let's show our entry's permissions!
1473 /// println!("{:?}: {:?}", entry.path(), metadata.permissions());
1475 /// println!("Couldn't get metadata for {:?}", entry.path());
1481 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1482 pub fn metadata(&self) -> io::Result<Metadata> {
1483 self.0.metadata().map(Metadata)
1486 /// Returns the file type for the file that this entry points at.
1488 /// This function will not traverse symlinks if this entry points at a
1491 /// # Platform-specific behavior
1493 /// On Windows and most Unix platforms this function is free (no extra
1494 /// system calls needed), but some Unix platforms may require the equivalent
1495 /// call to `symlink_metadata` to learn about the target file type.
1502 /// if let Ok(entries) = fs::read_dir(".") {
1503 /// for entry in entries {
1504 /// if let Ok(entry) = entry {
1505 /// // Here, `entry` is a `DirEntry`.
1506 /// if let Ok(file_type) = entry.file_type() {
1507 /// // Now let's show our entry's file type!
1508 /// println!("{:?}: {:?}", entry.path(), file_type);
1510 /// println!("Couldn't get file type for {:?}", entry.path());
1516 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1517 pub fn file_type(&self) -> io::Result<FileType> {
1518 self.0.file_type().map(FileType)
1521 /// Returns the bare file name of this directory entry without any other
1522 /// leading path component.
1529 /// if let Ok(entries) = fs::read_dir(".") {
1530 /// for entry in entries {
1531 /// if let Ok(entry) = entry {
1532 /// // Here, `entry` is a `DirEntry`.
1533 /// println!("{:?}", entry.file_name());
1538 #[stable(feature = "dir_entry_ext", since = "1.1.0")]
1539 pub fn file_name(&self) -> OsString {
1544 #[stable(feature = "dir_entry_debug", since = "1.13.0")]
1545 impl fmt::Debug for DirEntry {
1546 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1547 f.debug_tuple("DirEntry").field(&self.path()).finish()
1551 impl AsInner<fs_imp::DirEntry> for DirEntry {
1552 fn as_inner(&self) -> &fs_imp::DirEntry {
1557 /// Removes a file from the filesystem.
1559 /// Note that there is no
1560 /// guarantee that the file is immediately deleted (e.g., depending on
1561 /// platform, other open file descriptors may prevent immediate removal).
1563 /// # Platform-specific behavior
1565 /// This function currently corresponds to the `unlink` function on Unix
1566 /// and the `DeleteFile` function on Windows.
1567 /// Note that, this [may change in the future][changes].
1569 /// [changes]: ../io/index.html#platform-specific-behavior
1573 /// This function will return an error in the following situations, but is not
1574 /// limited to just these cases:
1576 /// * `path` points to a directory.
1577 /// * The file doesn't exist.
1578 /// * The user lacks permissions to remove the file.
1585 /// fn main() -> std::io::Result<()> {
1586 /// fs::remove_file("a.txt")?;
1590 #[stable(feature = "rust1", since = "1.0.0")]
1591 pub fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
1592 fs_imp::unlink(path.as_ref())
1595 /// Given a path, query the file system to get information about a file,
1598 /// This function will traverse symbolic links to query information about the
1599 /// destination file.
1601 /// # Platform-specific behavior
1603 /// This function currently corresponds to the `stat` function on Unix
1604 /// and the `GetFileAttributesEx` function on Windows.
1605 /// Note that, this [may change in the future][changes].
1607 /// [changes]: ../io/index.html#platform-specific-behavior
1611 /// This function will return an error in the following situations, but is not
1612 /// limited to just these cases:
1614 /// * The user lacks permissions to perform `metadata` call on `path`.
1615 /// * `path` does not exist.
1622 /// fn main() -> std::io::Result<()> {
1623 /// let attr = fs::metadata("/some/file/path.txt")?;
1624 /// // inspect attr ...
1628 #[stable(feature = "rust1", since = "1.0.0")]
1629 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1630 fs_imp::stat(path.as_ref()).map(Metadata)
1633 /// Query the metadata about a file without following symlinks.
1635 /// # Platform-specific behavior
1637 /// This function currently corresponds to the `lstat` function on Unix
1638 /// and the `GetFileAttributesEx` function on Windows.
1639 /// Note that, this [may change in the future][changes].
1641 /// [changes]: ../io/index.html#platform-specific-behavior
1645 /// This function will return an error in the following situations, but is not
1646 /// limited to just these cases:
1648 /// * The user lacks permissions to perform `metadata` call on `path`.
1649 /// * `path` does not exist.
1656 /// fn main() -> std::io::Result<()> {
1657 /// let attr = fs::symlink_metadata("/some/file/path.txt")?;
1658 /// // inspect attr ...
1662 #[stable(feature = "symlink_metadata", since = "1.1.0")]
1663 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<Metadata> {
1664 fs_imp::lstat(path.as_ref()).map(Metadata)
1667 /// Rename a file or directory to a new name, replacing the original file if
1668 /// `to` already exists.
1670 /// This will not work if the new name is on a different mount point.
1672 /// # Platform-specific behavior
1674 /// This function currently corresponds to the `rename` function on Unix
1675 /// and the `MoveFileEx` function with the `MOVEFILE_REPLACE_EXISTING` flag on Windows.
1677 /// Because of this, the behavior when both `from` and `to` exist differs. On
1678 /// Unix, if `from` is a directory, `to` must also be an (empty) directory. If
1679 /// `from` is not a directory, `to` must also be not a directory. In contrast,
1680 /// on Windows, `from` can be anything, but `to` must *not* be a directory.
1682 /// Note that, this [may change in the future][changes].
1684 /// [changes]: ../io/index.html#platform-specific-behavior
1688 /// This function will return an error in the following situations, but is not
1689 /// limited to just these cases:
1691 /// * `from` does not exist.
1692 /// * The user lacks permissions to view contents.
1693 /// * `from` and `to` are on separate filesystems.
1700 /// fn main() -> std::io::Result<()> {
1701 /// fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
1707 fs_imp::rename(from.as_ref(), to.as_ref())
1710 /// Copies the contents of one file to another. This function will also
1711 /// copy the permission bits of the original file to the destination file.
1713 /// This function will **overwrite** the contents of `to`.
1715 /// Note that if `from` and `to` both point to the same file, then the file
1716 /// will likely get truncated by this operation.
1718 /// On success, the total number of bytes copied is returned and it is equal to
1719 /// the length of the `to` file as reported by `metadata`.
1721 /// If you’re wanting to copy the contents of one file to another and you’re
1722 /// working with [`File`]s, see the [`io::copy`] function.
1724 /// [`io::copy`]: ../io/fn.copy.html
1725 /// [`File`]: ./struct.File.html
1727 /// # Platform-specific behavior
1729 /// This function currently corresponds to the `open` function in Unix
1730 /// with `O_RDONLY` for `from` and `O_WRONLY`, `O_CREAT`, and `O_TRUNC` for `to`.
1731 /// `O_CLOEXEC` is set for returned file descriptors.
1732 /// On Windows, this function currently corresponds to `CopyFileEx`. Alternate
1733 /// NTFS streams are copied but only the size of the main stream is returned by
1734 /// this function. On MacOS, this function corresponds to `fclonefileat` and
1736 /// Note that, this [may change in the future][changes].
1738 /// [changes]: ../io/index.html#platform-specific-behavior
1742 /// This function will return an error in the following situations, but is not
1743 /// limited to just these cases:
1745 /// * The `from` path is not a file.
1746 /// * The `from` file does not exist.
1747 /// * The current process does not have the permission rights to access
1748 /// `from` or write `to`.
1755 /// fn main() -> std::io::Result<()> {
1756 /// fs::copy("foo.txt", "bar.txt")?; // Copy foo.txt to bar.txt
1760 #[stable(feature = "rust1", since = "1.0.0")]
1761 pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<u64> {
1762 fs_imp::copy(from.as_ref(), to.as_ref())
1765 /// Creates a new hard link on the filesystem.
1767 /// The `dst` path will be a link pointing to the `src` path. Note that systems
1768 /// often require these two paths to both be located on the same filesystem.
1770 /// # Platform-specific behavior
1772 /// This function currently corresponds to the `link` function on Unix
1773 /// and the `CreateHardLink` function on Windows.
1774 /// Note that, this [may change in the future][changes].
1776 /// [changes]: ../io/index.html#platform-specific-behavior
1780 /// This function will return an error in the following situations, but is not
1781 /// limited to just these cases:
1783 /// * The `src` path is not a file or doesn't exist.
1790 /// fn main() -> std::io::Result<()> {
1791 /// fs::hard_link("a.txt", "b.txt")?; // Hard link a.txt to b.txt
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1797 fs_imp::link(src.as_ref(), dst.as_ref())
1800 /// Creates a new symbolic link on the filesystem.
1802 /// The `dst` path will be a symbolic link pointing to the `src` path.
1803 /// On Windows, this will be a file symlink, not a directory symlink;
1804 /// for this reason, the platform-specific [`std::os::unix::fs::symlink`]
1805 /// and [`std::os::windows::fs::symlink_file`] or [`symlink_dir`] should be
1806 /// used instead to make the intent explicit.
1808 /// [`std::os::unix::fs::symlink`]: ../os/unix/fs/fn.symlink.html
1809 /// [`std::os::windows::fs::symlink_file`]: ../os/windows/fs/fn.symlink_file.html
1810 /// [`symlink_dir`]: ../os/windows/fs/fn.symlink_dir.html
1818 /// fn main() -> std::io::Result<()> {
1819 /// fs::soft_link("a.txt", "b.txt")?;
1823 #[stable(feature = "rust1", since = "1.0.0")]
1826 reason = "replaced with std::os::unix::fs::symlink and \
1827 std::os::windows::fs::{symlink_file, symlink_dir}"
1829 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
1830 fs_imp::symlink(src.as_ref(), dst.as_ref())
1833 /// Reads a symbolic link, returning the file that the link points to.
1835 /// # Platform-specific behavior
1837 /// This function currently corresponds to the `readlink` function on Unix
1838 /// and the `CreateFile` function with `FILE_FLAG_OPEN_REPARSE_POINT` and
1839 /// `FILE_FLAG_BACKUP_SEMANTICS` flags on Windows.
1840 /// Note that, this [may change in the future][changes].
1842 /// [changes]: ../io/index.html#platform-specific-behavior
1846 /// This function will return an error in the following situations, but is not
1847 /// limited to just these cases:
1849 /// * `path` is not a symbolic link.
1850 /// * `path` does not exist.
1857 /// fn main() -> std::io::Result<()> {
1858 /// let path = fs::read_link("a.txt")?;
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1864 fs_imp::readlink(path.as_ref())
1867 /// Returns the canonical, absolute form of a path with all intermediate
1868 /// components normalized and symbolic links resolved.
1870 /// # Platform-specific behavior
1872 /// This function currently corresponds to the `realpath` function on Unix
1873 /// and the `CreateFile` and `GetFinalPathNameByHandle` functions on Windows.
1874 /// Note that, this [may change in the future][changes].
1876 /// On Windows, this converts the path to use [extended length path][path]
1877 /// syntax, which allows your program to use longer path names, but means you
1878 /// can only join backslash-delimited paths to it, and it may be incompatible
1879 /// with other applications (if passed to the application on the command-line,
1880 /// or written to a file another application may read).
1882 /// [changes]: ../io/index.html#platform-specific-behavior
1883 /// [path]: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
1887 /// This function will return an error in the following situations, but is not
1888 /// limited to just these cases:
1890 /// * `path` does not exist.
1891 /// * A non-final component in path is not a directory.
1898 /// fn main() -> std::io::Result<()> {
1899 /// let path = fs::canonicalize("../a/../foo.txt")?;
1903 #[stable(feature = "fs_canonicalize", since = "1.5.0")]
1904 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
1905 fs_imp::canonicalize(path.as_ref())
1908 /// Creates a new, empty directory at the provided path
1910 /// # Platform-specific behavior
1912 /// This function currently corresponds to the `mkdir` function on Unix
1913 /// and the `CreateDirectory` function on Windows.
1914 /// Note that, this [may change in the future][changes].
1916 /// [changes]: ../io/index.html#platform-specific-behavior
1918 /// **NOTE**: If a parent of the given path doesn't exist, this function will
1919 /// return an error. To create a directory and all its missing parents at the
1920 /// same time, use the [`create_dir_all`] function.
1924 /// This function will return an error in the following situations, but is not
1925 /// limited to just these cases:
1927 /// * User lacks permissions to create directory at `path`.
1928 /// * A parent of the given path doesn't exist. (To create a directory and all
1929 /// its missing parents at the same time, use the [`create_dir_all`]
1931 /// * `path` already exists.
1933 /// [`create_dir_all`]: fn.create_dir_all.html
1940 /// fn main() -> std::io::Result<()> {
1941 /// fs::create_dir("/some/dir")?;
1945 #[stable(feature = "rust1", since = "1.0.0")]
1946 pub fn create_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
1947 DirBuilder::new().create(path.as_ref())
1950 /// Recursively create a directory and all of its parent components if they
1953 /// # Platform-specific behavior
1955 /// This function currently corresponds to the `mkdir` function on Unix
1956 /// and the `CreateDirectory` function on Windows.
1957 /// Note that, this [may change in the future][changes].
1959 /// [changes]: ../io/index.html#platform-specific-behavior
1963 /// This function will return an error in the following situations, but is not
1964 /// limited to just these cases:
1966 /// * If any directory in the path specified by `path`
1967 /// does not already exist and it could not be created otherwise. The specific
1968 /// error conditions for when a directory is being created (after it is
1969 /// determined to not exist) are outlined by [`fs::create_dir`].
1971 /// Notable exception is made for situations where any of the directories
1972 /// specified in the `path` could not be created as it was being created concurrently.
1973 /// Such cases are considered to be successful. That is, calling `create_dir_all`
1974 /// concurrently from multiple threads or processes is guaranteed not to fail
1975 /// due to a race condition with itself.
1977 /// [`fs::create_dir`]: fn.create_dir.html
1984 /// fn main() -> std::io::Result<()> {
1985 /// fs::create_dir_all("/some/dir")?;
1989 #[stable(feature = "rust1", since = "1.0.0")]
1990 pub fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
1991 DirBuilder::new().recursive(true).create(path.as_ref())
1994 /// Removes an existing, empty directory.
1996 /// # Platform-specific behavior
1998 /// This function currently corresponds to the `rmdir` function on Unix
1999 /// and the `RemoveDirectory` function on Windows.
2000 /// Note that, this [may change in the future][changes].
2002 /// [changes]: ../io/index.html#platform-specific-behavior
2006 /// This function will return an error in the following situations, but is not
2007 /// limited to just these cases:
2009 /// * The user lacks permissions to remove the directory at the provided `path`.
2010 /// * The directory isn't empty.
2017 /// fn main() -> std::io::Result<()> {
2018 /// fs::remove_dir("/some/dir")?;
2022 #[stable(feature = "rust1", since = "1.0.0")]
2023 pub fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
2024 fs_imp::rmdir(path.as_ref())
2027 /// Removes a directory at this path, after removing all its contents. Use
2030 /// This function does **not** follow symbolic links and it will simply remove the
2031 /// symbolic link itself.
2033 /// # Platform-specific behavior
2035 /// This function currently corresponds to `opendir`, `lstat`, `rm` and `rmdir` functions on Unix
2036 /// and the `FindFirstFile`, `GetFileAttributesEx`, `DeleteFile`, and `RemoveDirectory` functions
2038 /// Note that, this [may change in the future][changes].
2040 /// [changes]: ../io/index.html#platform-specific-behavior
2044 /// See [`fs::remove_file`] and [`fs::remove_dir`].
2046 /// [`fs::remove_file`]: fn.remove_file.html
2047 /// [`fs::remove_dir`]: fn.remove_dir.html
2054 /// fn main() -> std::io::Result<()> {
2055 /// fs::remove_dir_all("/some/dir")?;
2059 #[stable(feature = "rust1", since = "1.0.0")]
2060 pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
2061 fs_imp::remove_dir_all(path.as_ref())
2064 /// Returns an iterator over the entries within a directory.
2066 /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`.
2067 /// New errors may be encountered after an iterator is initially constructed.
2069 /// [`io::Result`]: ../io/type.Result.html
2070 /// [`DirEntry`]: struct.DirEntry.html
2072 /// # Platform-specific behavior
2074 /// This function currently corresponds to the `opendir` function on Unix
2075 /// and the `FindFirstFile` function on Windows. Advancing the iterator
2076 /// currently corresponds to `readdir` on Unix and `FindNextFile` on Windows.
2077 /// Note that, this [may change in the future][changes].
2079 /// [changes]: ../io/index.html#platform-specific-behavior
2081 /// The order in which this iterator returns entries is platform and filesystem
2086 /// This function will return an error in the following situations, but is not
2087 /// limited to just these cases:
2089 /// * The provided `path` doesn't exist.
2090 /// * The process lacks permissions to view the contents.
2091 /// * The `path` points at a non-directory file.
2097 /// use std::fs::{self, DirEntry};
2098 /// use std::path::Path;
2100 /// // one possible implementation of walking a directory only visiting files
2101 /// fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
2102 /// if dir.is_dir() {
2103 /// for entry in fs::read_dir(dir)? {
2104 /// let entry = entry?;
2105 /// let path = entry.path();
2106 /// if path.is_dir() {
2107 /// visit_dirs(&path, cb)?;
2118 /// use std::{fs, io};
2120 /// fn main() -> io::Result<()> {
2121 /// let mut entries = fs::read_dir(".")?
2122 /// .map(|res| res.map(|e| e.path()))
2123 /// .collect::<Result<Vec<_>, io::Error>>()?;
2125 /// // The order in which `read_dir` returns entries is not guaranteed. If reproducible
2126 /// // ordering is required the entries should be explicitly sorted.
2130 /// // The entries have now been sorted by their path.
2135 #[stable(feature = "rust1", since = "1.0.0")]
2136 pub fn read_dir<P: AsRef<Path>>(path: P) -> io::Result<ReadDir> {
2137 fs_imp::readdir(path.as_ref()).map(ReadDir)
2140 /// Changes the permissions found on a file or a directory.
2142 /// # Platform-specific behavior
2144 /// This function currently corresponds to the `chmod` function on Unix
2145 /// and the `SetFileAttributes` function on Windows.
2146 /// Note that, this [may change in the future][changes].
2148 /// [changes]: ../io/index.html#platform-specific-behavior
2152 /// This function will return an error in the following situations, but is not
2153 /// limited to just these cases:
2155 /// * `path` does not exist.
2156 /// * The user lacks the permission to change attributes of the file.
2163 /// fn main() -> std::io::Result<()> {
2164 /// let mut perms = fs::metadata("foo.txt")?.permissions();
2165 /// perms.set_readonly(true);
2166 /// fs::set_permissions("foo.txt", perms)?;
2170 #[stable(feature = "set_permissions", since = "1.1.0")]
2171 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: Permissions) -> io::Result<()> {
2172 fs_imp::set_perm(path.as_ref(), perm.0)
2176 /// Creates a new set of options with default mode/security settings for all
2177 /// platforms and also non-recursive.
2182 /// use std::fs::DirBuilder;
2184 /// let builder = DirBuilder::new();
2186 #[stable(feature = "dir_builder", since = "1.6.0")]
2187 pub fn new() -> DirBuilder {
2188 DirBuilder { inner: fs_imp::DirBuilder::new(), recursive: false }
2191 /// Indicates that directories should be created recursively, creating all
2192 /// parent directories. Parents that do not exist are created with the same
2193 /// security and permissions settings.
2195 /// This option defaults to `false`.
2200 /// use std::fs::DirBuilder;
2202 /// let mut builder = DirBuilder::new();
2203 /// builder.recursive(true);
2205 #[stable(feature = "dir_builder", since = "1.6.0")]
2206 pub fn recursive(&mut self, recursive: bool) -> &mut Self {
2207 self.recursive = recursive;
2211 /// Creates the specified directory with the options configured in this
2214 /// It is considered an error if the directory already exists unless
2215 /// recursive mode is enabled.
2220 /// use std::fs::{self, DirBuilder};
2222 /// let path = "/tmp/foo/bar/baz";
2223 /// DirBuilder::new()
2224 /// .recursive(true)
2225 /// .create(path).unwrap();
2227 /// assert!(fs::metadata(path).unwrap().is_dir());
2229 #[stable(feature = "dir_builder", since = "1.6.0")]
2230 pub fn create<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
2231 self._create(path.as_ref())
2234 fn _create(&self, path: &Path) -> io::Result<()> {
2235 if self.recursive { self.create_dir_all(path) } else { self.inner.mkdir(path) }
2238 fn create_dir_all(&self, path: &Path) -> io::Result<()> {
2239 if path == Path::new("") {
2243 match self.inner.mkdir(path) {
2244 Ok(()) => return Ok(()),
2245 Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
2246 Err(_) if path.is_dir() => return Ok(()),
2247 Err(e) => return Err(e),
2249 match path.parent() {
2250 Some(p) => self.create_dir_all(p)?,
2252 return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree"));
2255 match self.inner.mkdir(path) {
2257 Err(_) if path.is_dir() => Ok(()),
2263 impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
2264 fn as_inner_mut(&mut self) -> &mut fs_imp::DirBuilder {
2269 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
2271 use crate::io::prelude::*;
2273 use crate::fs::{self, File, OpenOptions};
2274 use crate::io::{ErrorKind, SeekFrom};
2275 use crate::path::Path;
2277 use crate::sys_common::io::test::{tmpdir, TempDir};
2280 use rand::{rngs::StdRng, RngCore, SeedableRng};
2283 use crate::os::unix::fs::symlink as symlink_dir;
2285 use crate::os::unix::fs::symlink as symlink_file;
2287 use crate::os::unix::fs::symlink as symlink_junction;
2289 use crate::os::windows::fs::{symlink_dir, symlink_file};
2291 use crate::sys::fs::symlink_junction;
2293 macro_rules! check {
2297 Err(e) => panic!("{} failed with: {}", stringify!($e), e),
2303 macro_rules! error {
2304 ($e:expr, $s:expr) => {
2306 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2307 Err(ref err) => assert!(
2308 err.raw_os_error() == Some($s),
2309 format!("`{}` did not have a code of `{}`", err, $s)
2316 macro_rules! error {
2317 ($e:expr, $s:expr) => {
2318 error_contains!($e, $s)
2322 macro_rules! error_contains {
2323 ($e:expr, $s:expr) => {
2325 Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
2326 Err(ref err) => assert!(
2327 err.to_string().contains($s),
2328 format!("`{}` did not contain `{}`", err, $s)
2334 // Several test fail on windows if the user does not have permission to
2335 // create symlinks (the `SeCreateSymbolicLinkPrivilege`). Instead of
2336 // disabling these test on Windows, use this function to test whether we
2337 // have permission, and return otherwise. This way, we still don't run these
2338 // tests most of the time, but at least we do if the user has the right
2340 pub fn got_symlink_permission(tmpdir: &TempDir) -> bool {
2344 let link = tmpdir.join("some_hopefully_unique_link_name");
2346 match symlink_file(r"nonexisting_target", link) {
2348 // ERROR_PRIVILEGE_NOT_HELD = 1314
2349 Err(ref err) if err.raw_os_error() == Some(1314) => false,
2355 fn file_test_io_smoke_test() {
2356 let message = "it's alright. have a good time";
2357 let tmpdir = tmpdir();
2358 let filename = &tmpdir.join("file_rt_io_file_test.txt");
2360 let mut write_stream = check!(File::create(filename));
2361 check!(write_stream.write(message.as_bytes()));
2364 let mut read_stream = check!(File::open(filename));
2365 let mut read_buf = [0; 1028];
2366 let read_str = match check!(read_stream.read(&mut read_buf)) {
2367 0 => panic!("shouldn't happen"),
2368 n => str::from_utf8(&read_buf[..n]).unwrap().to_string(),
2370 assert_eq!(read_str, message);
2372 check!(fs::remove_file(filename));
2376 fn invalid_path_raises() {
2377 let tmpdir = tmpdir();
2378 let filename = &tmpdir.join("file_that_does_not_exist.txt");
2379 let result = File::open(filename);
2381 #[cfg(all(unix, not(target_os = "vxworks")))]
2382 error!(result, "No such file or directory");
2383 #[cfg(target_os = "vxworks")]
2384 error!(result, "no such file or directory");
2386 error!(result, 2); // ERROR_FILE_NOT_FOUND
2390 fn file_test_iounlinking_invalid_path_should_raise_condition() {
2391 let tmpdir = tmpdir();
2392 let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
2394 let result = fs::remove_file(filename);
2396 #[cfg(all(unix, not(target_os = "vxworks")))]
2397 error!(result, "No such file or directory");
2398 #[cfg(target_os = "vxworks")]
2399 error!(result, "no such file or directory");
2401 error!(result, 2); // ERROR_FILE_NOT_FOUND
2405 fn file_test_io_non_positional_read() {
2406 let message: &str = "ten-four";
2407 let mut read_mem = [0; 8];
2408 let tmpdir = tmpdir();
2409 let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
2411 let mut rw_stream = check!(File::create(filename));
2412 check!(rw_stream.write(message.as_bytes()));
2415 let mut read_stream = check!(File::open(filename));
2417 let read_buf = &mut read_mem[0..4];
2418 check!(read_stream.read(read_buf));
2421 let read_buf = &mut read_mem[4..8];
2422 check!(read_stream.read(read_buf));
2425 check!(fs::remove_file(filename));
2426 let read_str = str::from_utf8(&read_mem).unwrap();
2427 assert_eq!(read_str, message);
2431 fn file_test_io_seek_and_tell_smoke_test() {
2432 let message = "ten-four";
2433 let mut read_mem = [0; 4];
2434 let set_cursor = 4 as u64;
2435 let tell_pos_pre_read;
2436 let tell_pos_post_read;
2437 let tmpdir = tmpdir();
2438 let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
2440 let mut rw_stream = check!(File::create(filename));
2441 check!(rw_stream.write(message.as_bytes()));
2444 let mut read_stream = check!(File::open(filename));
2445 check!(read_stream.seek(SeekFrom::Start(set_cursor)));
2446 tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
2447 check!(read_stream.read(&mut read_mem));
2448 tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
2450 check!(fs::remove_file(filename));
2451 let read_str = str::from_utf8(&read_mem).unwrap();
2452 assert_eq!(read_str, &message[4..8]);
2453 assert_eq!(tell_pos_pre_read, set_cursor);
2454 assert_eq!(tell_pos_post_read, message.len() as u64);
2458 fn file_test_io_seek_and_write() {
2459 let initial_msg = "food-is-yummy";
2460 let overwrite_msg = "-the-bar!!";
2461 let final_msg = "foo-the-bar!!";
2463 let mut read_mem = [0; 13];
2464 let tmpdir = tmpdir();
2465 let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
2467 let mut rw_stream = check!(File::create(filename));
2468 check!(rw_stream.write(initial_msg.as_bytes()));
2469 check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
2470 check!(rw_stream.write(overwrite_msg.as_bytes()));
2473 let mut read_stream = check!(File::open(filename));
2474 check!(read_stream.read(&mut read_mem));
2476 check!(fs::remove_file(filename));
2477 let read_str = str::from_utf8(&read_mem).unwrap();
2478 assert!(read_str == final_msg);
2482 fn file_test_io_seek_shakedown() {
2484 let initial_msg = "qwer-asdf-zxcv";
2485 let chunk_one: &str = "qwer";
2486 let chunk_two: &str = "asdf";
2487 let chunk_three: &str = "zxcv";
2488 let mut read_mem = [0; 4];
2489 let tmpdir = tmpdir();
2490 let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
2492 let mut rw_stream = check!(File::create(filename));
2493 check!(rw_stream.write(initial_msg.as_bytes()));
2496 let mut read_stream = check!(File::open(filename));
2498 check!(read_stream.seek(SeekFrom::End(-4)));
2499 check!(read_stream.read(&mut read_mem));
2500 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
2502 check!(read_stream.seek(SeekFrom::Current(-9)));
2503 check!(read_stream.read(&mut read_mem));
2504 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
2506 check!(read_stream.seek(SeekFrom::Start(0)));
2507 check!(read_stream.read(&mut read_mem));
2508 assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
2510 check!(fs::remove_file(filename));
2514 fn file_test_io_eof() {
2515 let tmpdir = tmpdir();
2516 let filename = tmpdir.join("file_rt_io_file_test_eof.txt");
2517 let mut buf = [0; 256];
2519 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2520 let mut rw = check!(oo.open(&filename));
2521 assert_eq!(check!(rw.read(&mut buf)), 0);
2522 assert_eq!(check!(rw.read(&mut buf)), 0);
2524 check!(fs::remove_file(&filename));
2529 fn file_test_io_read_write_at() {
2530 use crate::os::unix::fs::FileExt;
2532 let tmpdir = tmpdir();
2533 let filename = tmpdir.join("file_rt_io_file_test_read_write_at.txt");
2534 let mut buf = [0; 256];
2535 let write1 = "asdf";
2536 let write2 = "qwer-";
2537 let write3 = "-zxcv";
2538 let content = "qwer-asdf-zxcv";
2540 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2541 let mut rw = check!(oo.open(&filename));
2542 assert_eq!(check!(rw.write_at(write1.as_bytes(), 5)), write1.len());
2543 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2544 assert_eq!(check!(rw.read_at(&mut buf, 5)), write1.len());
2545 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2546 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2547 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2548 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok("\0\0\0\0\0"));
2549 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 0);
2550 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2551 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2552 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2553 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2554 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2555 assert_eq!(check!(rw.read_at(&mut buf[..write2.len()], 0)), write2.len());
2556 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2557 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2558 assert_eq!(check!(rw.write_at(write3.as_bytes(), 9)), write3.len());
2559 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2562 let mut read = check!(File::open(&filename));
2563 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2564 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2565 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 0);
2566 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2567 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2568 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2569 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 9);
2570 assert_eq!(check!(read.read(&mut buf)), write3.len());
2571 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2572 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2573 assert_eq!(check!(read.read_at(&mut buf, 0)), content.len());
2574 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2575 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2576 assert_eq!(check!(read.read_at(&mut buf, 14)), 0);
2577 assert_eq!(check!(read.read_at(&mut buf, 15)), 0);
2578 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2580 check!(fs::remove_file(&filename));
2585 fn set_get_unix_permissions() {
2586 use crate::os::unix::fs::PermissionsExt;
2588 let tmpdir = tmpdir();
2589 let filename = &tmpdir.join("set_get_unix_permissions");
2590 check!(fs::create_dir(filename));
2593 check!(fs::set_permissions(filename, fs::Permissions::from_mode(0)));
2594 let metadata0 = check!(fs::metadata(filename));
2595 assert_eq!(mask & metadata0.permissions().mode(), 0);
2597 check!(fs::set_permissions(filename, fs::Permissions::from_mode(0o1777)));
2598 let metadata1 = check!(fs::metadata(filename));
2599 #[cfg(all(unix, not(target_os = "vxworks")))]
2600 assert_eq!(mask & metadata1.permissions().mode(), 0o1777);
2601 #[cfg(target_os = "vxworks")]
2602 assert_eq!(mask & metadata1.permissions().mode(), 0o0777);
2607 fn file_test_io_seek_read_write() {
2608 use crate::os::windows::fs::FileExt;
2610 let tmpdir = tmpdir();
2611 let filename = tmpdir.join("file_rt_io_file_test_seek_read_write.txt");
2612 let mut buf = [0; 256];
2613 let write1 = "asdf";
2614 let write2 = "qwer-";
2615 let write3 = "-zxcv";
2616 let content = "qwer-asdf-zxcv";
2618 let oo = OpenOptions::new().create_new(true).write(true).read(true).clone();
2619 let mut rw = check!(oo.open(&filename));
2620 assert_eq!(check!(rw.seek_write(write1.as_bytes(), 5)), write1.len());
2621 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2622 assert_eq!(check!(rw.seek_read(&mut buf, 5)), write1.len());
2623 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2624 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2625 assert_eq!(check!(rw.seek(SeekFrom::Start(0))), 0);
2626 assert_eq!(check!(rw.write(write2.as_bytes())), write2.len());
2627 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2628 assert_eq!(check!(rw.read(&mut buf)), write1.len());
2629 assert_eq!(str::from_utf8(&buf[..write1.len()]), Ok(write1));
2630 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 9);
2631 assert_eq!(check!(rw.seek_read(&mut buf[..write2.len()], 0)), write2.len());
2632 assert_eq!(str::from_utf8(&buf[..write2.len()]), Ok(write2));
2633 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 5);
2634 assert_eq!(check!(rw.seek_write(write3.as_bytes(), 9)), write3.len());
2635 assert_eq!(check!(rw.seek(SeekFrom::Current(0))), 14);
2638 let mut read = check!(File::open(&filename));
2639 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2640 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2641 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2642 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2643 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2644 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2645 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2646 assert_eq!(check!(read.seek(SeekFrom::End(-5))), 9);
2647 assert_eq!(check!(read.read(&mut buf)), write3.len());
2648 assert_eq!(str::from_utf8(&buf[..write3.len()]), Ok(write3));
2649 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2650 assert_eq!(check!(read.seek_read(&mut buf, 0)), content.len());
2651 assert_eq!(str::from_utf8(&buf[..content.len()]), Ok(content));
2652 assert_eq!(check!(read.seek(SeekFrom::Current(0))), 14);
2653 assert_eq!(check!(read.seek_read(&mut buf, 14)), 0);
2654 assert_eq!(check!(read.seek_read(&mut buf, 15)), 0);
2656 check!(fs::remove_file(&filename));
2660 fn file_test_stat_is_correct_on_is_file() {
2661 let tmpdir = tmpdir();
2662 let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
2664 let mut opts = OpenOptions::new();
2665 let mut fs = check!(opts.read(true).write(true).create(true).open(filename));
2667 fs.write(msg.as_bytes()).unwrap();
2669 let fstat_res = check!(fs.metadata());
2670 assert!(fstat_res.is_file());
2672 let stat_res_fn = check!(fs::metadata(filename));
2673 assert!(stat_res_fn.is_file());
2674 let stat_res_meth = check!(filename.metadata());
2675 assert!(stat_res_meth.is_file());
2676 check!(fs::remove_file(filename));
2680 fn file_test_stat_is_correct_on_is_dir() {
2681 let tmpdir = tmpdir();
2682 let filename = &tmpdir.join("file_stat_correct_on_is_dir");
2683 check!(fs::create_dir(filename));
2684 let stat_res_fn = check!(fs::metadata(filename));
2685 assert!(stat_res_fn.is_dir());
2686 let stat_res_meth = check!(filename.metadata());
2687 assert!(stat_res_meth.is_dir());
2688 check!(fs::remove_dir(filename));
2692 fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
2693 let tmpdir = tmpdir();
2694 let dir = &tmpdir.join("fileinfo_false_on_dir");
2695 check!(fs::create_dir(dir));
2696 assert!(!dir.is_file());
2697 check!(fs::remove_dir(dir));
2701 fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
2702 let tmpdir = tmpdir();
2703 let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
2704 check!(check!(File::create(file)).write(b"foo"));
2705 assert!(file.exists());
2706 check!(fs::remove_file(file));
2707 assert!(!file.exists());
2711 fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
2712 let tmpdir = tmpdir();
2713 let dir = &tmpdir.join("before_and_after_dir");
2714 assert!(!dir.exists());
2715 check!(fs::create_dir(dir));
2716 assert!(dir.exists());
2717 assert!(dir.is_dir());
2718 check!(fs::remove_dir(dir));
2719 assert!(!dir.exists());
2723 fn file_test_directoryinfo_readdir() {
2724 let tmpdir = tmpdir();
2725 let dir = &tmpdir.join("di_readdir");
2726 check!(fs::create_dir(dir));
2729 let f = dir.join(&format!("{}.txt", n));
2730 let mut w = check!(File::create(&f));
2731 let msg_str = format!("{}{}", prefix, n.to_string());
2732 let msg = msg_str.as_bytes();
2733 check!(w.write(msg));
2735 let files = check!(fs::read_dir(dir));
2736 let mut mem = [0; 4];
2738 let f = f.unwrap().path();
2740 let n = f.file_stem().unwrap();
2741 check!(check!(File::open(&f)).read(&mut mem));
2742 let read_str = str::from_utf8(&mem).unwrap();
2743 let expected = format!("{}{}", prefix, n.to_str().unwrap());
2744 assert_eq!(expected, read_str);
2746 check!(fs::remove_file(&f));
2748 check!(fs::remove_dir(dir));
2752 fn file_create_new_already_exists_error() {
2753 let tmpdir = tmpdir();
2754 let file = &tmpdir.join("file_create_new_error_exists");
2755 check!(fs::File::create(file));
2756 let e = fs::OpenOptions::new().write(true).create_new(true).open(file).unwrap_err();
2757 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2761 fn mkdir_path_already_exists_error() {
2762 let tmpdir = tmpdir();
2763 let dir = &tmpdir.join("mkdir_error_twice");
2764 check!(fs::create_dir(dir));
2765 let e = fs::create_dir(dir).unwrap_err();
2766 assert_eq!(e.kind(), ErrorKind::AlreadyExists);
2770 fn recursive_mkdir() {
2771 let tmpdir = tmpdir();
2772 let dir = tmpdir.join("d1/d2");
2773 check!(fs::create_dir_all(&dir));
2774 assert!(dir.is_dir())
2778 fn recursive_mkdir_failure() {
2779 let tmpdir = tmpdir();
2780 let dir = tmpdir.join("d1");
2781 let file = dir.join("f1");
2783 check!(fs::create_dir_all(&dir));
2784 check!(File::create(&file));
2786 let result = fs::create_dir_all(&file);
2788 assert!(result.is_err());
2792 fn concurrent_recursive_mkdir() {
2795 let mut dir = dir.join("a");
2797 dir = dir.join("a");
2799 let mut join = vec![];
2801 let dir = dir.clone();
2802 join.push(thread::spawn(move || {
2803 check!(fs::create_dir_all(&dir));
2807 // No `Display` on result of `join()`
2808 join.drain(..).map(|join| join.join().unwrap()).count();
2813 fn recursive_mkdir_slash() {
2814 check!(fs::create_dir_all(Path::new("/")));
2818 fn recursive_mkdir_dot() {
2819 check!(fs::create_dir_all(Path::new(".")));
2823 fn recursive_mkdir_empty() {
2824 check!(fs::create_dir_all(Path::new("")));
2828 fn recursive_rmdir() {
2829 let tmpdir = tmpdir();
2830 let d1 = tmpdir.join("d1");
2831 let dt = d1.join("t");
2832 let dtt = dt.join("t");
2833 let d2 = tmpdir.join("d2");
2834 let canary = d2.join("do_not_delete");
2835 check!(fs::create_dir_all(&dtt));
2836 check!(fs::create_dir_all(&d2));
2837 check!(check!(File::create(&canary)).write(b"foo"));
2838 check!(symlink_junction(&d2, &dt.join("d2")));
2839 let _ = symlink_file(&canary, &d1.join("canary"));
2840 check!(fs::remove_dir_all(&d1));
2842 assert!(!d1.is_dir());
2843 assert!(canary.exists());
2847 fn recursive_rmdir_of_symlink() {
2848 // test we do not recursively delete a symlink but only dirs.
2849 let tmpdir = tmpdir();
2850 let link = tmpdir.join("d1");
2851 let dir = tmpdir.join("d2");
2852 let canary = dir.join("do_not_delete");
2853 check!(fs::create_dir_all(&dir));
2854 check!(check!(File::create(&canary)).write(b"foo"));
2855 check!(symlink_junction(&dir, &link));
2856 check!(fs::remove_dir_all(&link));
2858 assert!(!link.is_dir());
2859 assert!(canary.exists());
2863 // only Windows makes a distinction between file and directory symlinks.
2865 fn recursive_rmdir_of_file_symlink() {
2866 let tmpdir = tmpdir();
2867 if !got_symlink_permission(&tmpdir) {
2871 let f1 = tmpdir.join("f1");
2872 let f2 = tmpdir.join("f2");
2873 check!(check!(File::create(&f1)).write(b"foo"));
2874 check!(symlink_file(&f1, &f2));
2875 match fs::remove_dir_all(&f2) {
2876 Ok(..) => panic!("wanted a failure"),
2882 fn unicode_path_is_dir() {
2883 assert!(Path::new(".").is_dir());
2884 assert!(!Path::new("test/stdtest/fs.rs").is_dir());
2886 let tmpdir = tmpdir();
2888 let mut dirpath = tmpdir.path().to_path_buf();
2889 dirpath.push("test-가一ー你好");
2890 check!(fs::create_dir(&dirpath));
2891 assert!(dirpath.is_dir());
2893 let mut filepath = dirpath;
2894 filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
2895 check!(File::create(&filepath)); // ignore return; touch only
2896 assert!(!filepath.is_dir());
2897 assert!(filepath.exists());
2901 fn unicode_path_exists() {
2902 assert!(Path::new(".").exists());
2903 assert!(!Path::new("test/nonexistent-bogus-path").exists());
2905 let tmpdir = tmpdir();
2906 let unicode = tmpdir.path();
2907 let unicode = unicode.join("test-각丁ー再见");
2908 check!(fs::create_dir(&unicode));
2909 assert!(unicode.exists());
2910 assert!(!Path::new("test/unicode-bogus-path-각丁ー再见").exists());
2914 fn copy_file_does_not_exist() {
2915 let from = Path::new("test/nonexistent-bogus-path");
2916 let to = Path::new("test/other-bogus-path");
2918 match fs::copy(&from, &to) {
2921 assert!(!from.exists());
2922 assert!(!to.exists());
2928 fn copy_src_does_not_exist() {
2929 let tmpdir = tmpdir();
2930 let from = Path::new("test/nonexistent-bogus-path");
2931 let to = tmpdir.join("out.txt");
2932 check!(check!(File::create(&to)).write(b"hello"));
2933 assert!(fs::copy(&from, &to).is_err());
2934 assert!(!from.exists());
2935 let mut v = Vec::new();
2936 check!(check!(File::open(&to)).read_to_end(&mut v));
2937 assert_eq!(v, b"hello");
2942 let tmpdir = tmpdir();
2943 let input = tmpdir.join("in.txt");
2944 let out = tmpdir.join("out.txt");
2946 check!(check!(File::create(&input)).write(b"hello"));
2947 check!(fs::copy(&input, &out));
2948 let mut v = Vec::new();
2949 check!(check!(File::open(&out)).read_to_end(&mut v));
2950 assert_eq!(v, b"hello");
2952 assert_eq!(check!(input.metadata()).permissions(), check!(out.metadata()).permissions());
2956 fn copy_file_dst_dir() {
2957 let tmpdir = tmpdir();
2958 let out = tmpdir.join("out");
2960 check!(File::create(&out));
2961 match fs::copy(&*out, tmpdir.path()) {
2968 fn copy_file_dst_exists() {
2969 let tmpdir = tmpdir();
2970 let input = tmpdir.join("in");
2971 let output = tmpdir.join("out");
2973 check!(check!(File::create(&input)).write("foo".as_bytes()));
2974 check!(check!(File::create(&output)).write("bar".as_bytes()));
2975 check!(fs::copy(&input, &output));
2977 let mut v = Vec::new();
2978 check!(check!(File::open(&output)).read_to_end(&mut v));
2979 assert_eq!(v, b"foo".to_vec());
2983 fn copy_file_src_dir() {
2984 let tmpdir = tmpdir();
2985 let out = tmpdir.join("out");
2987 match fs::copy(tmpdir.path(), &out) {
2991 assert!(!out.exists());
2995 fn copy_file_preserves_perm_bits() {
2996 let tmpdir = tmpdir();
2997 let input = tmpdir.join("in.txt");
2998 let out = tmpdir.join("out.txt");
3000 let attr = check!(check!(File::create(&input)).metadata());
3001 let mut p = attr.permissions();
3002 p.set_readonly(true);
3003 check!(fs::set_permissions(&input, p));
3004 check!(fs::copy(&input, &out));
3005 assert!(check!(out.metadata()).permissions().readonly());
3006 check!(fs::set_permissions(&input, attr.permissions()));
3007 check!(fs::set_permissions(&out, attr.permissions()));
3012 fn copy_file_preserves_streams() {
3014 check!(check!(File::create(tmp.join("in.txt:bunny"))).write("carrot".as_bytes()));
3015 assert_eq!(check!(fs::copy(tmp.join("in.txt"), tmp.join("out.txt"))), 0);
3016 assert_eq!(check!(tmp.join("out.txt").metadata()).len(), 0);
3017 let mut v = Vec::new();
3018 check!(check!(File::open(tmp.join("out.txt:bunny"))).read_to_end(&mut v));
3019 assert_eq!(v, b"carrot".to_vec());
3023 fn copy_file_returns_metadata_len() {
3025 let in_path = tmp.join("in.txt");
3026 let out_path = tmp.join("out.txt");
3027 check!(check!(File::create(&in_path)).write(b"lettuce"));
3029 check!(check!(File::create(tmp.join("in.txt:bunny"))).write(b"carrot"));
3030 let copied_len = check!(fs::copy(&in_path, &out_path));
3031 assert_eq!(check!(out_path.metadata()).len(), copied_len);
3035 fn copy_file_follows_dst_symlink() {
3037 if !got_symlink_permission(&tmp) {
3041 let in_path = tmp.join("in.txt");
3042 let out_path = tmp.join("out.txt");
3043 let out_path_symlink = tmp.join("out_symlink.txt");
3045 check!(fs::write(&in_path, "foo"));
3046 check!(fs::write(&out_path, "bar"));
3047 check!(symlink_file(&out_path, &out_path_symlink));
3049 check!(fs::copy(&in_path, &out_path_symlink));
3051 assert!(check!(out_path_symlink.symlink_metadata()).file_type().is_symlink());
3052 assert_eq!(check!(fs::read(&out_path_symlink)), b"foo".to_vec());
3053 assert_eq!(check!(fs::read(&out_path)), b"foo".to_vec());
3057 fn symlinks_work() {
3058 let tmpdir = tmpdir();
3059 if !got_symlink_permission(&tmpdir) {
3063 let input = tmpdir.join("in.txt");
3064 let out = tmpdir.join("out.txt");
3066 check!(check!(File::create(&input)).write("foobar".as_bytes()));
3067 check!(symlink_file(&input, &out));
3068 assert!(check!(out.symlink_metadata()).file_type().is_symlink());
3069 assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len());
3070 let mut v = Vec::new();
3071 check!(check!(File::open(&out)).read_to_end(&mut v));
3072 assert_eq!(v, b"foobar".to_vec());
3076 fn symlink_noexist() {
3077 // Symlinks can point to things that don't exist
3078 let tmpdir = tmpdir();
3079 if !got_symlink_permission(&tmpdir) {
3083 // Use a relative path for testing. Symlinks get normalized by Windows,
3084 // so we may not get the same path back for absolute paths
3085 check!(symlink_file(&"foo", &tmpdir.join("bar")));
3086 assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))).to_str().unwrap(), "foo");
3092 // directory symlink
3094 check!(fs::read_link(r"C:\Users\All Users")).to_str().unwrap(),
3099 check!(fs::read_link(r"C:\Users\Default User")).to_str().unwrap(),
3102 // junction with special permissions
3104 check!(fs::read_link(r"C:\Documents and Settings\")).to_str().unwrap(),
3108 let tmpdir = tmpdir();
3109 let link = tmpdir.join("link");
3110 if !got_symlink_permission(&tmpdir) {
3113 check!(symlink_file(&"foo", &link));
3114 assert_eq!(check!(fs::read_link(&link)).to_str().unwrap(), "foo");
3118 fn readlink_not_symlink() {
3119 let tmpdir = tmpdir();
3120 match fs::read_link(tmpdir.path()) {
3121 Ok(..) => panic!("wanted a failure"),
3128 let tmpdir = tmpdir();
3129 let input = tmpdir.join("in.txt");
3130 let out = tmpdir.join("out.txt");
3132 check!(check!(File::create(&input)).write("foobar".as_bytes()));
3133 check!(fs::hard_link(&input, &out));
3134 assert_eq!(check!(fs::metadata(&out)).len(), check!(fs::metadata(&input)).len());
3135 assert_eq!(check!(fs::metadata(&out)).len(), check!(input.metadata()).len());
3136 let mut v = Vec::new();
3137 check!(check!(File::open(&out)).read_to_end(&mut v));
3138 assert_eq!(v, b"foobar".to_vec());
3140 // can't link to yourself
3141 match fs::hard_link(&input, &input) {
3142 Ok(..) => panic!("wanted a failure"),
3145 // can't link to something that doesn't exist
3146 match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
3147 Ok(..) => panic!("wanted a failure"),
3154 let tmpdir = tmpdir();
3155 let file = tmpdir.join("in.txt");
3157 check!(File::create(&file));
3158 let attr = check!(fs::metadata(&file));
3159 assert!(!attr.permissions().readonly());
3160 let mut p = attr.permissions();
3161 p.set_readonly(true);
3162 check!(fs::set_permissions(&file, p.clone()));
3163 let attr = check!(fs::metadata(&file));
3164 assert!(attr.permissions().readonly());
3166 match fs::set_permissions(&tmpdir.join("foo"), p.clone()) {
3167 Ok(..) => panic!("wanted an error"),
3171 p.set_readonly(false);
3172 check!(fs::set_permissions(&file, p));
3177 let tmpdir = tmpdir();
3178 let path = tmpdir.join("in.txt");
3180 let file = check!(File::create(&path));
3181 let attr = check!(fs::metadata(&path));
3182 assert!(!attr.permissions().readonly());
3183 let mut p = attr.permissions();
3184 p.set_readonly(true);
3185 check!(file.set_permissions(p.clone()));
3186 let attr = check!(fs::metadata(&path));
3187 assert!(attr.permissions().readonly());
3189 p.set_readonly(false);
3190 check!(file.set_permissions(p));
3194 fn sync_doesnt_kill_anything() {
3195 let tmpdir = tmpdir();
3196 let path = tmpdir.join("in.txt");
3198 let mut file = check!(File::create(&path));
3199 check!(file.sync_all());
3200 check!(file.sync_data());
3201 check!(file.write(b"foo"));
3202 check!(file.sync_all());
3203 check!(file.sync_data());
3207 fn truncate_works() {
3208 let tmpdir = tmpdir();
3209 let path = tmpdir.join("in.txt");
3211 let mut file = check!(File::create(&path));
3212 check!(file.write(b"foo"));
3213 check!(file.sync_all());
3215 // Do some simple things with truncation
3216 assert_eq!(check!(file.metadata()).len(), 3);
3217 check!(file.set_len(10));
3218 assert_eq!(check!(file.metadata()).len(), 10);
3219 check!(file.write(b"bar"));
3220 check!(file.sync_all());
3221 assert_eq!(check!(file.metadata()).len(), 10);
3223 let mut v = Vec::new();
3224 check!(check!(File::open(&path)).read_to_end(&mut v));
3225 assert_eq!(v, b"foobar\0\0\0\0".to_vec());
3227 // Truncate to a smaller length, don't seek, and then write something.
3228 // Ensure that the intermediate zeroes are all filled in (we have `seek`ed
3229 // past the end of the file).
3230 check!(file.set_len(2));
3231 assert_eq!(check!(file.metadata()).len(), 2);
3232 check!(file.write(b"wut"));
3233 check!(file.sync_all());
3234 assert_eq!(check!(file.metadata()).len(), 9);
3235 let mut v = Vec::new();
3236 check!(check!(File::open(&path)).read_to_end(&mut v));
3237 assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
3242 use crate::fs::OpenOptions as OO;
3243 fn c<T: Clone>(t: &T) -> T {
3247 let tmpdir = tmpdir();
3249 let mut r = OO::new();
3251 let mut w = OO::new();
3253 let mut rw = OO::new();
3254 rw.read(true).write(true);
3255 let mut a = OO::new();
3257 let mut ra = OO::new();
3258 ra.read(true).append(true);
3261 let invalid_options = 87; // ERROR_INVALID_PARAMETER
3262 #[cfg(all(unix, not(target_os = "vxworks")))]
3263 let invalid_options = "Invalid argument";
3264 #[cfg(target_os = "vxworks")]
3265 let invalid_options = "invalid argument";
3267 // Test various combinations of creation modes and access modes.
3270 // creation mode | read | write | read-write | append | read-append |
3271 // :-----------------------|:-----:|:-----:|:----------:|:------:|:-----------:|
3272 // not set (open existing) | X | X | X | X | X |
3273 // create | | X | X | X | X |
3274 // truncate | | X | X | | |
3275 // create and truncate | | X | X | | |
3276 // create_new | | X | X | X | X |
3278 // tested in reverse order, so 'create_new' creates the file, and 'open existing' opens it.
3281 check!(c(&w).create_new(true).open(&tmpdir.join("a")));
3282 check!(c(&w).create(true).truncate(true).open(&tmpdir.join("a")));
3283 check!(c(&w).truncate(true).open(&tmpdir.join("a")));
3284 check!(c(&w).create(true).open(&tmpdir.join("a")));
3285 check!(c(&w).open(&tmpdir.join("a")));
3288 error!(c(&r).create_new(true).open(&tmpdir.join("b")), invalid_options);
3289 error!(c(&r).create(true).truncate(true).open(&tmpdir.join("b")), invalid_options);
3290 error!(c(&r).truncate(true).open(&tmpdir.join("b")), invalid_options);
3291 error!(c(&r).create(true).open(&tmpdir.join("b")), invalid_options);
3292 check!(c(&r).open(&tmpdir.join("a"))); // try opening the file created with write_only
3295 check!(c(&rw).create_new(true).open(&tmpdir.join("c")));
3296 check!(c(&rw).create(true).truncate(true).open(&tmpdir.join("c")));
3297 check!(c(&rw).truncate(true).open(&tmpdir.join("c")));
3298 check!(c(&rw).create(true).open(&tmpdir.join("c")));
3299 check!(c(&rw).open(&tmpdir.join("c")));
3302 check!(c(&a).create_new(true).open(&tmpdir.join("d")));
3303 error!(c(&a).create(true).truncate(true).open(&tmpdir.join("d")), invalid_options);
3304 error!(c(&a).truncate(true).open(&tmpdir.join("d")), invalid_options);
3305 check!(c(&a).create(true).open(&tmpdir.join("d")));
3306 check!(c(&a).open(&tmpdir.join("d")));
3309 check!(c(&ra).create_new(true).open(&tmpdir.join("e")));
3310 error!(c(&ra).create(true).truncate(true).open(&tmpdir.join("e")), invalid_options);
3311 error!(c(&ra).truncate(true).open(&tmpdir.join("e")), invalid_options);
3312 check!(c(&ra).create(true).open(&tmpdir.join("e")));
3313 check!(c(&ra).open(&tmpdir.join("e")));
3315 // Test opening a file without setting an access mode
3316 let mut blank = OO::new();
3317 error!(blank.create(true).open(&tmpdir.join("f")), invalid_options);
3320 check!(check!(File::create(&tmpdir.join("h"))).write("foobar".as_bytes()));
3322 // Test write fails for read-only
3323 check!(r.open(&tmpdir.join("h")));
3325 let mut f = check!(r.open(&tmpdir.join("h")));
3326 assert!(f.write("wut".as_bytes()).is_err());
3329 // Test write overwrites
3331 let mut f = check!(c(&w).open(&tmpdir.join("h")));
3332 check!(f.write("baz".as_bytes()));
3335 let mut f = check!(c(&r).open(&tmpdir.join("h")));
3336 let mut b = vec![0; 6];
3337 check!(f.read(&mut b));
3338 assert_eq!(b, "bazbar".as_bytes());
3341 // Test truncate works
3343 let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
3344 check!(f.write("foo".as_bytes()));
3346 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3348 // Test append works
3349 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
3351 let mut f = check!(c(&a).open(&tmpdir.join("h")));
3352 check!(f.write("bar".as_bytes()));
3354 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
3356 // Test .append(true) equals .write(true).append(true)
3358 let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
3359 check!(f.write("baz".as_bytes()));
3361 assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 9);
3365 fn _assert_send_sync() {
3366 fn _assert_send_sync<T: Send + Sync>() {}
3367 _assert_send_sync::<OpenOptions>();
3372 let mut bytes = [0; 1024];
3373 StdRng::from_entropy().fill_bytes(&mut bytes);
3375 let tmpdir = tmpdir();
3377 check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
3378 let mut v = Vec::new();
3379 check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
3380 assert!(v == &bytes[..]);
3384 fn write_then_read() {
3385 let mut bytes = [0; 1024];
3386 StdRng::from_entropy().fill_bytes(&mut bytes);
3388 let tmpdir = tmpdir();
3390 check!(fs::write(&tmpdir.join("test"), &bytes[..]));
3391 let v = check!(fs::read(&tmpdir.join("test")));
3392 assert!(v == &bytes[..]);
3394 check!(fs::write(&tmpdir.join("not-utf8"), &[0xFF]));
3396 fs::read_to_string(&tmpdir.join("not-utf8")),
3397 "stream did not contain valid UTF-8"
3401 check!(fs::write(&tmpdir.join("utf8"), s.as_bytes()));
3402 let string = check!(fs::read_to_string(&tmpdir.join("utf8")));
3403 assert_eq!(string, s);
3407 fn file_try_clone() {
3408 let tmpdir = tmpdir();
3410 let mut f1 = check!(
3411 OpenOptions::new().read(true).write(true).create(true).open(&tmpdir.join("test"))
3413 let mut f2 = check!(f1.try_clone());
3415 check!(f1.write_all(b"hello world"));
3416 check!(f1.seek(SeekFrom::Start(2)));
3418 let mut buf = vec![];
3419 check!(f2.read_to_end(&mut buf));
3420 assert_eq!(buf, b"llo world");
3423 check!(f1.write_all(b"!"));
3427 #[cfg(not(windows))]
3428 fn unlink_readonly() {
3429 let tmpdir = tmpdir();
3430 let path = tmpdir.join("file");
3431 check!(File::create(&path));
3432 let mut perm = check!(fs::metadata(&path)).permissions();
3433 perm.set_readonly(true);
3434 check!(fs::set_permissions(&path, perm));
3435 check!(fs::remove_file(&path));
3439 fn mkdir_trailing_slash() {
3440 let tmpdir = tmpdir();
3441 let path = tmpdir.join("file");
3442 check!(fs::create_dir_all(&path.join("a/")));
3446 fn canonicalize_works_simple() {
3447 let tmpdir = tmpdir();
3448 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3449 let file = tmpdir.join("test");
3450 File::create(&file).unwrap();
3451 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3455 fn realpath_works() {
3456 let tmpdir = tmpdir();
3457 if !got_symlink_permission(&tmpdir) {
3461 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3462 let file = tmpdir.join("test");
3463 let dir = tmpdir.join("test2");
3464 let link = dir.join("link");
3465 let linkdir = tmpdir.join("test3");
3467 File::create(&file).unwrap();
3468 fs::create_dir(&dir).unwrap();
3469 symlink_file(&file, &link).unwrap();
3470 symlink_dir(&dir, &linkdir).unwrap();
3472 assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
3474 assert_eq!(fs::canonicalize(&tmpdir).unwrap(), tmpdir);
3475 assert_eq!(fs::canonicalize(&file).unwrap(), file);
3476 assert_eq!(fs::canonicalize(&link).unwrap(), file);
3477 assert_eq!(fs::canonicalize(&linkdir).unwrap(), dir);
3478 assert_eq!(fs::canonicalize(&linkdir.join("link")).unwrap(), file);
3482 fn realpath_works_tricky() {
3483 let tmpdir = tmpdir();
3484 if !got_symlink_permission(&tmpdir) {
3488 let tmpdir = fs::canonicalize(tmpdir.path()).unwrap();
3489 let a = tmpdir.join("a");
3490 let b = a.join("b");
3491 let c = b.join("c");
3492 let d = a.join("d");
3493 let e = d.join("e");
3494 let f = a.join("f");
3496 fs::create_dir_all(&b).unwrap();
3497 fs::create_dir_all(&d).unwrap();
3498 File::create(&f).unwrap();
3499 if cfg!(not(windows)) {
3500 symlink_file("../d/e", &c).unwrap();
3501 symlink_file("../f", &e).unwrap();
3504 symlink_file(r"..\d\e", &c).unwrap();
3505 symlink_file(r"..\f", &e).unwrap();
3508 assert_eq!(fs::canonicalize(&c).unwrap(), f);
3509 assert_eq!(fs::canonicalize(&e).unwrap(), f);
3513 fn dir_entry_methods() {
3514 let tmpdir = tmpdir();
3516 fs::create_dir_all(&tmpdir.join("a")).unwrap();
3517 File::create(&tmpdir.join("b")).unwrap();
3519 for file in tmpdir.path().read_dir().unwrap().map(|f| f.unwrap()) {
3520 let fname = file.file_name();
3521 match fname.to_str() {
3523 assert!(file.file_type().unwrap().is_dir());
3524 assert!(file.metadata().unwrap().is_dir());
3527 assert!(file.file_type().unwrap().is_file());
3528 assert!(file.metadata().unwrap().is_file());
3530 f => panic!("unknown file name: {:?}", f),
3536 fn dir_entry_debug() {
3537 let tmpdir = tmpdir();
3538 File::create(&tmpdir.join("b")).unwrap();
3539 let mut read_dir = tmpdir.path().read_dir().unwrap();
3540 let dir_entry = read_dir.next().unwrap().unwrap();
3541 let actual = format!("{:?}", dir_entry);
3542 let expected = format!("DirEntry({:?})", dir_entry.0.path());
3543 assert_eq!(actual, expected);
3547 fn read_dir_not_found() {
3548 let res = fs::read_dir("/path/that/does/not/exist");
3549 assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound);
3553 fn create_dir_all_with_junctions() {
3554 let tmpdir = tmpdir();
3555 let target = tmpdir.join("target");
3557 let junction = tmpdir.join("junction");
3558 let b = junction.join("a/b");
3560 let link = tmpdir.join("link");
3561 let d = link.join("c/d");
3563 fs::create_dir(&target).unwrap();
3565 check!(symlink_junction(&target, &junction));
3566 check!(fs::create_dir_all(&b));
3567 // the junction itself is not a directory, but `is_dir()` on a Path
3569 assert!(junction.is_dir());
3570 assert!(b.exists());
3572 if !got_symlink_permission(&tmpdir) {
3575 check!(symlink_dir(&target, &link));
3576 check!(fs::create_dir_all(&d));
3577 assert!(link.is_dir());
3578 assert!(d.exists());
3582 fn metadata_access_times() {
3583 let tmpdir = tmpdir();
3585 let b = tmpdir.join("b");
3586 File::create(&b).unwrap();
3588 let a = check!(fs::metadata(&tmpdir.path()));
3589 let b = check!(fs::metadata(&b));
3591 assert_eq!(check!(a.accessed()), check!(a.accessed()));
3592 assert_eq!(check!(a.modified()), check!(a.modified()));
3593 assert_eq!(check!(b.accessed()), check!(b.modified()));
3595 if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
3596 check!(a.created());
3597 check!(b.created());
3600 if cfg!(target_os = "linux") {
3601 // Not always available
3602 match (a.created(), b.created()) {
3603 (Ok(t1), Ok(t2)) => assert!(t1 <= t2),
3605 if e1.kind() == ErrorKind::Other && e2.kind() == ErrorKind::Other => {}
3607 "creation time must be always supported or not supported: {:?} {:?}",