2

如何检查是否可以创建文件或可以向其中写入数据?这是我的代码,但我认为,如果文件是可写的,它就无法处理......有人可以告诉我,怎么做吗?

bool joinFiles(const char * outFile) {
try {
    ofstream arrayData(outFile);
    //do something
    // ...
    //

    // write data
    arrayData << "blahblah" << endl;   

} catch (const char *ex) {
    return false;
}
return true;
}
4

1 回答 1

4

如何检查是否可以创建文件或可以向其中写入数据?

默认情况下,流不会抛出异常(它们可以配置为通过 抛出异常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-24T15:16:51.417 回答