`Path.exists` is not safe against time-of-creation, time-of-use (TOCTOU)
bugs.
`OpenOptions.create_new` on the other hand is atomic, so not prone to
this kind of problems.
where
P: AsRef<Path>,
{
- if file_path.as_ref().exists() {
- // `io::Error` is used instead of a variant on `FileError` because there is already a
- // nightly-only `File::create_new` method
- return Err(FileError::Io(io::Error::new(
- io::ErrorKind::Other,
- "file already exists",
- )));
- }
let mut f = OpenOptions::new()
- .create(true)
+ .create_new(true)
.read(true)
.write(true)
.truncate(true)