Skip to content

Commit 91fd628

Browse files
committed
Auto merge of #65429 - Timmmm:withoptions, r=Mark-Simulacrum
Add File::with_options This provides a more fluent API to create files with options, and also avoids the need to import OpenOptions. This implements @aldanor's [suggestion](rust-lang/rfcs#2615 (comment)) which was popular.
2 parents f39205b + c8150cb commit 91fd628

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

src/libstd/fs.rs

+35-2
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use crate::time::SystemTime;
2929
///
3030
/// # Examples
3131
///
32-
/// Creates a new file and write bytes to it:
32+
/// Creates a new file and write bytes to it (you can also use [`write`]):
3333
///
3434
/// ```no_run
3535
/// use std::fs::File;
@@ -42,7 +42,7 @@ use crate::time::SystemTime;
4242
/// }
4343
/// ```
4444
///
45-
/// Read the contents of a file into a [`String`]:
45+
/// Read the contents of a file into a [`String`] (you can also use [`read`]):
4646
///
4747
/// ```no_run
4848
/// use std::fs::File;
@@ -89,6 +89,8 @@ use crate::time::SystemTime;
8989
/// [`Write`]: ../io/trait.Write.html
9090
/// [`BufReader<R>`]: ../io/struct.BufReader.html
9191
/// [`sync_all`]: struct.File.html#method.sync_all
92+
/// [`read`]: fn.read.html
93+
/// [`write`]: fn.write.html
9294
#[stable(feature = "rust1", since = "1.0.0")]
9395
pub struct File {
9496
inner: fs_imp::File,
@@ -397,6 +399,37 @@ impl File {
397399
OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
398400
}
399401

402+
/// Returns a new OpenOptions object.
403+
///
404+
/// This function returns a new OpenOptions object that you can use to
405+
/// open or create a file with specific options if `open()` or `create()`
406+
/// are not appropriate.
407+
///
408+
/// It is equivalent to `OpenOptions::new()` but allows you to write more
409+
/// readable code. Instead of `OpenOptions::new().read(true).open("foo.txt")`
410+
/// you can write `File::with_options().read(true).open("foo.txt"). This
411+
/// also avoids the need to import `OpenOptions`.
412+
///
413+
/// See the [`OpenOptions::new`] function for more details.
414+
///
415+
/// [`OpenOptions::new`]: struct.OpenOptions.html#method.new
416+
///
417+
/// # Examples
418+
///
419+
/// ```no_run
420+
/// #![feature(with_options)]
421+
/// use std::fs::File;
422+
///
423+
/// fn main() -> std::io::Result<()> {
424+
/// let mut f = File::with_options().read(true).open("foo.txt")?;
425+
/// Ok(())
426+
/// }
427+
/// ```
428+
#[unstable(feature = "with_options", issue = "65439")]
429+
pub fn with_options() -> OpenOptions {
430+
OpenOptions::new()
431+
}
432+
400433
/// Attempts to sync all OS-internal metadata to disk.
401434
///
402435
/// This function will attempt to ensure that all in-memory data reaches the

0 commit comments

Comments
 (0)