C++ substitution of ios::noreplace

∥☆過路亽.° 提交于 2019-12-22 18:24:59

问题


I'm using fstream to open a file for write. I don't want to overwrite an existing file so after some searching, I found ios::noreplace. But when I compile this:

#include <fstream>
using namespace std;
//......Did something else.
ofstream fout;
fout.open(outputFile,ios::noreplace);//outputFile is a C string

I get an error

 error: ‘noreplace’ is not a member of ‘std::ios’

I'm just wondering is there any std:: subsitution for ios::noreplace?


回答1:


Some searching on the internet reveals that you can add an existence check manually by attempting to open in "input" mode:

std::fstream myfile("thefile.txt", std::ios::in);

if (myfile)
{
    // error, file exists!
}
else
{
    myfile.close();
    myfile.open("thefile.txt", std::ios::out);  // OK now
}



回答2:


noreplace never got into the standard. About four seconds of googling yields: http://www.devx.com/tips/Tip/14544

In pre-standard C++, certain implementations of offered the flags ios::nocreate and ios::noreplace for controlling file creation. These flags were too platform-specific and never made it into the standard library, which supersedes the deprecated, pre-standard header. However, you can achieve the functionality of these obsolete flags rather easily.

fstream fs(fname, ios_base::in);// attempt open for read
if (!fs)
{
    // file doesn't exist; create a new one
    fs.open(fname, ios_base::out);
}
else //ok, file exists; close and reopen in write mode
{
     // Should throw an error
}



回答3:


The suggested answers are risky since they have race conditions. Unless you can guarantee nobody will ever create that file while your are running this test, you should not use it.

As a workaround, use the non-portable method (on Linux for example open with O_CREAT|O_EXCL).

You can either use the resulting handle with code like boost to wrap it into an ofstream, or in this case use open() only to check and then create a new ofstream on the file (the latter assumes nobody deletes/renames the file in-between and thus might still have a race condition).

C++ not providing ANY safe way to create a file is a bad joke and likely the cause of quite a few security holes. You have to love standards that encourage bad practices by making writing correct code impossible.



来源:https://stackoverflow.com/questions/9251581/c-substitution-of-iosnoreplace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!