确定文件是否可以在C++中创建/不是只读
问题描述:
如何检查是否可以创建文件或可以向其中写入数据?这是我的代码,但我认为,它不处理,如果该文件是可写的...任何人都可以告诉我,如何做到这一点?确定文件是否可以在C++中创建/不是只读
bool joinFiles(const char * outFile) {
try {
ofstream arrayData(outFile);
//do something
// ...
//
// write data
arrayData << "blahblah" << endl;
} catch (const char *ex) {
return false;
}
return true;
}
答
如何检查,如果可以创建文件或数据可写呢?
流不扔在默认情况下的异常(它们可以被配置为通过std::basic_ios::exceptions()
抛出异常),所以在检查文件是否已经打开,使用std::ofstream::is_open()
:
ofstream arrayData(outFile);
if (arrayData.is_open())
{
// File is writeable, but may not have existed
// prior to the construction of 'arrayData'.
// Check success of output operation also.
if (arrayData << "blahblah" << endl)
{
// File was opened and was written to.
return true;
}
}
// File was not opened or the write to it failed.
return false;
以写模式打开的文件,如果打开你可以写 – 2013-03-24 15:12:50