C++读写异常处理
如下所示,使用ofstream打开不存在的文件时不会抛出异常,程序正常结束。
#include <fstream>
#include <sstream>
using namespace std;
ofstream ofs("ofstream.txt");
ofs.write(buffer, sizeof(char)*17);
ofs.close();
Streams by default do not throw exceptions on error, they set flags. You can make them throw exceptions by using the stream’s exception() member function:
failure if an error occurred (the error state flag is not goodbit) and exceptions() is set to throw for that state.
If an internal operation throws an exception, it is caught and badbit is set. If exceptions() is set for badbit, the exception is rethrown.
先对状态标记符进行判断,再进行后续的操作
ofstream ofs("ofstream.txt");
if (!ofs.bad())
{
ofs << "Writing to a basic_ofstream object..." << endl;
ofs.close();
}
C读写异常处理
C中文件不存在时不加判断则会抛出错误。
FILE *fp;
char str[] = "This is runoob.com";
fp = fopen( "file.txt" , "w" );
fwrite(str, sizeof(str) , 1, fp );
fclose(fp);
打开文件出错时,fopen() 将返回一个空指针,也就是 NULL,我们可以利用这一点来判断文件是否打开成功,请看下面的代码:
FILE *fp;
if( (fp=fopen("D:\\demo.txt","rb") == NULL ){
printf("Fail to open file!\n");
exit(0);
}
我们通过判断 fopen() 的返回值是否和 NULL 相等来判断是否打开失败:如果 fopen() 的返回值为 NULL,那么 fp 的值也为 NULL,此时 if 的判断条件成立,表示文件打开失败。
以上代码是文件操作的规范写法,读者在打开文件时一定要判断文件是否打开成功,因为一旦打开失败,后续操作就都没法进行了,往往以“结束程序”告终。