Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ open file for writing only if does not exists

Tags:

c++

c

file

std

I would like to open a file for writing with the standard library, but the file open should fail if the file already exists.

From what I can read in the documentation, ofstream::open only allows appending or truncating.

I could of course try to open for reading to check if the file exists, and reopen for writing if it doesn't, but there is no guarantee that the file will not be created by another process inbetween.

Could someone confirm this is not possible in C++ with the standard library (std::iostream) or with the C functions (FILE* functions)

like image 628
galinette Avatar asked Oct 23 '25 00:10

galinette


2 Answers

Since C11 (and thus also in C++17), for fopen you can use mode "x" — exclusive mode, see this:

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.

like image 191
PiotrNycz Avatar answered Oct 25 '25 15:10

PiotrNycz


There are no fstream ways of doing this, but std::fopen is as much C++ as std::sin.

If you absolutely must have an fstream object of this file and you need the atomic check, you should first call fopen then on success, fclose and fstream::open:

std::ofstream create_new_file_for_writing()
{
    FILE* fp = nullptr;
    std::string fname;
    do {
        fname = random_file_name(); 
        fp = fopen(fname.c_str(), "wx");
    } while(!fp);
    // here the file is created and you "own" the filename
    fclose(fp);
    return std::ostream(fname);
}
like image 20
Borislav Stanimirov Avatar answered Oct 25 '25 15:10

Borislav Stanimirov