Is there a way to create and open a file if it does not exist, but does not work otherwise?

OpenOptions doesn't seem to support this scenario, and the existing file will be truncated or overwritten.

+8
rust
source share
3 answers

Unlike Rust 1.9.0, there is OpenOptions::create_new , which allows you to safely and atomically guarantee that you are creating a new file and that your command will not work otherwise.

+5
source share

This is possible in C11 or directly using the low-level OS API functions.

If you use C11, fopen allows you to open the file in "wx" mode.

Otherwise, on Linux, you must pass both O_CREAT and O_EXCL to the open(3) function. Or on Windows, go CREATE_NEW to the dwCreationDisposition parameter of the CreateFile() function.


EDIT: I initially overlooked the fact that the open function was updated to C11.

+4
source share

Update: As Mathieu David noted in the comments. exists() from std::path::Path can be used to check if a path exists.

Old answer:

In C, checking for a file / path name is usually done with:

 ! access(filename, F_OK) 

access returns 0 if the file exists, provided that you have the necessary permissions.

I quickly looked through my own Rust equivalent and found nothing. Thus, for this you may need libc::access .

+2
source share

All Articles