about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorTim Hutt <tdhutt@gmail.com>2019-10-07 13:32:07 +0100
committerTim Hutt <timh@graphcore.ai>2019-10-15 21:19:08 +0100
commit6cefcb0b54a52c5507362d3ae33bc11843580ae1 (patch)
tree23c87a6b04b4743b5737d67b06c4073f7a4d197f /src/libstd
parent237d54ff6c4fb3577e02d4c5af02813c11b63d01 (diff)
downloadrust-6cefcb0b54a52c5507362d3ae33bc11843580ae1.tar.gz
rust-6cefcb0b54a52c5507362d3ae33bc11843580ae1.zip
Add File::with_options
This provides a more fluent API to create files with options, and also avoids the need to import OpenOptions.
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/fs.rs35
1 files changed, 33 insertions, 2 deletions
diff --git a/src/libstd/fs.rs b/src/libstd/fs.rs
index fc26dcb3211..ce1680fde22 100644
--- a/src/libstd/fs.rs
+++ b/src/libstd/fs.rs
@@ -29,7 +29,7 @@ use crate::time::SystemTime;
 ///
 /// # Examples
 ///
-/// Creates a new file and write bytes to it:
+/// Creates a new file and write bytes to it (you can also use [`std::fs::write`]):
 ///
 /// ```no_run
 /// use std::fs::File;
@@ -42,7 +42,7 @@ use crate::time::SystemTime;
 /// }
 /// ```
 ///
-/// Read the contents of a file into a [`String`]:
+/// Read the contents of a file into a [`String`] (you can also use [`std::fs::read`]):
 ///
 /// ```no_run
 /// use std::fs::File;
@@ -397,6 +397,37 @@ impl File {
         OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
     }
 
+    /// Returns a new OpenOptions object.
+    ///
+    /// This function returns a new OpenOptions object that you can use to
+    /// open or create a file with specific options if `open()` or `create()`
+    /// are not appropriate.
+    ///
+    /// It is equivalent to `OpenOptions::new()` but allows you to write more
+    /// readable code. Instead of `OpenOptions::new().read(true).open("foo.txt")`
+    /// you can write `File::with_options().read(true).open("foo.txt"). This
+    /// also avoids the need to import `OpenOptions`.
+    ///
+    /// See the [`OpenOptions::new`] function for more details.
+    ///
+    /// [`OpenOptions::new`]: struct.OpenOptions.html#method.new
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// #![feature(with_options)]
+    /// use std::fs::File;
+    ///
+    /// fn main() -> std::io::Result<()> {
+    ///     let mut f = File::with_options().read(true).open("foo.txt")?;
+    ///     Ok(())
+    /// }
+    /// ```
+    #[unstable(feature = "with_options", issue = "65439")]
+    pub fn with_options() -> OpenOptions {
+        OpenOptions::new()
+    }
+
     /// Attempts to sync all OS-internal metadata to disk.
     ///
     /// This function will attempt to ensure that all in-memory data reaches the