Skip to content

Commit ce41d2f

Browse files
authored
Rollup merge of rust-lang#98801 - joshtriplett:file-create-new, r=thomcc
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.
2 parents 983f4da + e540425 commit ce41d2f

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

library/std/src/fs.rs

+29
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,35 @@ impl File {
377377
OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
378378
}
379379

380+
/// Creates a new file in read-write mode; error if the file exists.
381+
///
382+
/// This function will create a file if it does not exist, or return an error if it does. This
383+
/// way, if the call succeeds, the file returned is guaranteed to be new.
384+
///
385+
/// This option is useful because it is atomic. Otherwise between checking whether a file
386+
/// exists and creating a new one, the file may have been created by another process (a TOCTOU
387+
/// race condition / attack).
388+
///
389+
/// This can also be written using
390+
/// `File::options().read(true).write(true).create_new(true).open(...)`.
391+
///
392+
/// # Examples
393+
///
394+
/// ```no_run
395+
/// #![feature(file_create_new)]
396+
///
397+
/// use std::fs::File;
398+
///
399+
/// fn main() -> std::io::Result<()> {
400+
/// let mut f = File::create_new("foo.txt")?;
401+
/// Ok(())
402+
/// }
403+
/// ```
404+
#[unstable(feature = "file_create_new", issue = "none")]
405+
pub fn create_new<P: AsRef<Path>>(path: P) -> io::Result<File> {
406+
OpenOptions::new().read(true).write(true).create_new(true).open(path.as_ref())
407+
}
408+
380409
/// Returns a new OpenOptions object.
381410
///
382411
/// This function returns a new OpenOptions object that you can use to

0 commit comments

Comments
 (0)