Skip to content

Commit

Permalink
Rollup merge of rust-lang#98801 - joshtriplett:file-create-new, r=thomcc
Browse files Browse the repository at this point in the history
Add a `File::create_new` constructor

We have `File::create` for creating a file or opening an existing file,
but the secure way to guarantee creating a new file requires a longhand
invocation via `OpenOptions`.

Add `File::create_new` to handle this case, to make it easier for people
to do secure file creation.
  • Loading branch information
Dylan-DPC authored Aug 26, 2022
2 parents 983f4da + e540425 commit ce41d2f
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions library/std/src/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,35 @@ impl File {
OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
}

/// Creates a new file in read-write mode; error if the file exists.
///
/// This function will create a file if it does not exist, or return an error if it does. This
/// way, if the call succeeds, the file returned is guaranteed to be new.
///
/// This option is useful because it is atomic. Otherwise between checking whether a file
/// exists and creating a new one, the file may have been created by another process (a TOCTOU
/// race condition / attack).
///
/// This can also be written using
/// `File::options().read(true).write(true).create_new(true).open(...)`.
///
/// # Examples
///
/// ```no_run
/// #![feature(file_create_new)]
///
/// use std::fs::File;
///
/// fn main() -> std::io::Result<()> {
/// let mut f = File::create_new("foo.txt")?;
/// Ok(())
/// }
/// ```
#[unstable(feature = "file_create_new", issue = "none")]
pub fn create_new<P: AsRef<Path>>(path: P) -> io::Result<File> {
OpenOptions::new().read(true).write(true).create_new(true).open(path.as_ref())
}

/// Returns a new OpenOptions object.
///
/// This function returns a new OpenOptions object that you can use to
Expand Down

0 comments on commit ce41d2f

Please sign in to comment.