Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a File::create_new constructor #98801

Merged
merged 1 commit into from
Aug 29, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions library/std/src/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,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.
///
joshtriplett marked this conversation as resolved.
Show resolved Hide resolved
/// 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> {
joshtriplett marked this conversation as resolved.
Show resolved Hide resolved
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