Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to create and open a file if it doesn't exist but fail otherwise?

Tags:

rust

It looks like OpenOptions does not support this scenario and an existing file will either be truncated or overwritten.

like image 607
hwiechers Avatar asked Feb 25 '16 19:02

hwiechers


People also ask

How do you create a file that doesn't exist?

You can use many ways to create a file if it does not exist. The most common way is to use the open() function and pass the different modes as per your requirement. Other ways are using the pathlib module or the os module and checking the file's existing condition.

Which command create and import file if file does not exist?

Python Create File if Not Exists Using the open() Function From the file modes explained above, we can pass a+ to add the text to the file or create it first if it does not exist. The w+ mode will truncate the file and then open it in write mode, so if we do not want the file to be truncated, we should use the a+ mode.

Which mode is used to create new file if the file does not exist?

a: It indicates append mode. w+: It's used to create the file if it doesn't already exist, and then it's used to open it in write mode. r+: It opens the required file in both modes (read and write). a+: If the file does not exist, first it is created and afterward opened in append mode.

How do you create a file in C if it does not exist?

The fopen() function creates the file if it does not exist. Notes: The fopen() function is not supported for files that are opened with the attributes type=record and ab+, rb+, or wb+ Use the w, w+, wb, w+b, and wb+ parameters with care; data in existing files of the same name will be lost.


1 Answers

As of Rust 1.9.0, there is OpenOptions::create_new which enables you to safely and atomically ensure that you are creating a new file, and that your command will fail otherwise.

like image 98
David Roundy Avatar answered Sep 22 '22 01:09

David Roundy