diff options
| author | Josh Triplett <josh@joshtriplett.org> | 2022-07-01 23:30:47 -0700 |
|---|---|---|
| committer | Josh Triplett <josh@joshtriplett.org> | 2022-07-12 21:30:36 -0700 |
| commit | e540425a2425819be4717ff0e4217c40cc52c99f (patch) | |
| tree | 82d31d343449b06fbd8b036302173c6e2162295f | |
| parent | 9a6fa4f118d88991458549464d960aa1e495541b (diff) | |
| download | rust-e540425a2425819be4717ff0e4217c40cc52c99f.tar.gz rust-e540425a2425819be4717ff0e4217c40cc52c99f.zip | |
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.
| -rw-r--r-- | library/std/src/fs.rs | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/library/std/src/fs.rs b/library/std/src/fs.rs index f46997b807a..97093ffb46f 100644 --- a/library/std/src/fs.rs +++ b/library/std/src/fs.rs @@ -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. + /// + /// 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 |
