我使用fstream对象将数据写入文本文件。我给它写了一些初始数据,然后在循环中写入更多数据。每次写入文件流之前,我都会检查它是否打开。这不必要吗?我应该在创建fstream对象后立即检查一次吗?
基本上,我这样做:
#define STOP 32700 // some value that indicates no more data is available
#include <string>
#include <exception>
#include <fstream>
int main (int argc, char* argv[])
{
try {
double data[5] {};
const std::string output_file_name {"name.txt"}
std::fstream outputFile (output_file_name, std::ios::out | std::ios::trunc);
if (outputFile.is_open()) // successfully opened file
outputFile << "initial text\n";
else // if text file could not be opened
throw Fstream_Exception;
/* do some other stuff (in various threads) */
do { // ok, now get data and write it to the file!
getData(&data[0]);
if (outputFile.is_open())
outputFile << data[0] << '\n';
else
throw Fstream_Exception;
} while (data[0] != STOP);
}
catch (Fstream_Exception& fstream_exception) {
/* handle exception */
}
}
答案 0 :(得分:4)
发生错误时,流本身可以抛出异常。只需使用其exceptions()
方法并传递您希望它检测的错误类型。这比在每次操作后检查状态标志更方便。