如何检查,是否可以创建文件或是否可以写入数据?这是我的代码,但我认为,如果文件是可写的,它无法处理......有人可以告诉我,该怎么做?
bool joinFiles(const char * outFile) {
try {
ofstream arrayData(outFile);
//do something
// ...
//
// write data
arrayData << "blahblah" << endl;
} catch (const char *ex) {
return false;
}
return true;
}
答案 0 :(得分:4)
如何检查,是否可以创建文件或是否可以写入数据?
默认情况下,Streams不会抛出异常(可以将它们配置为通过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;