xxhxx
xxhxx

Reputation: 901

In C++, How to safely create a file if it's not exist, but not to open it if it's exist?

If I directly using ios::out to open a file, then it will overwrite it or modify it if the file was existed.

But if I check if there is a file named "XXX" with ios::in, and create it with ios::out if it's not exist, the file "XXX" may be created by another program during this period, then the file "XXX" will be overwrote or be modified just like the first case.

How can I safely create a file with fstream in C++?

Upvotes: 0

Views: 1708

Answers (4)

xxhxx
xxhxx

Reputation: 901

Answer for everyone.

In C++23, we can use std::ios::noreplace to accomplish this operation.

Upvotes: 1

Jose
Jose

Reputation: 3460

A proper solution to your problem in the C++ standard library is only available since since C++17 - not in C++11 (and in the C standard library since C11):

std::fopen (and C's fopen) now allows you to use the subspecifier x which forces the function to fail if the file already exists (https://en.cppreference.com/w/cpp/io/c/fopen)

File access mode flag "x" can optionally be appended to "w" or "w+" specifiers. This flag forces the function to fail if the file exists, instead of overwriting it. (C++17)

Upvotes: 5

Jean-Marc Volle
Jean-Marc Volle

Reputation: 3333

If you are using microsoft C++ you can do the following:

    std::fstream file;
    bool ok = file.open("path_to_my_file", std::ios::app, _SH_DENYWR); // open the file in non sharing write mode
    if (ok)
    {
     // you now have exclusive access to the file
    }
    else 
    {
      // try later (for instance)
    }

This is not standard C++ but this will ensure whoever opens the file first will get it and will not erase any existing content (ios::app)

Upvotes: 0

Hussam
Hussam

Reputation: 93

To avoid overwriting, use ios::app when writing to an existing file to append your new data to it instead of overwriting it.

Upvotes: -2

Related Questions