Материал из C\C++ эксперт
checks for errors opening file
#include <fstream>
#include <iostream>
using namespace std;
int main(){
ifstream file;
file.open("a:test.dat");
if( !file )
cout << "\nCan"t open GROUP.DAT";
else
cout << "\nFile opened successfully.";
cout << "\nfile = " << file;
cout << "\nError state = " << file.rdstate();
cout << "\ngood() = " << file.good();
cout << "\neof() = " << file.eof();
cout << "\nfail() = " << file.fail();
cout << "\nbad() = " << file.bad() << endl;
file.close();
return 0;
}
Handle basic exception
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <exception>
using namespace std;
void readIntegerFile(const string& fileName, vector<int>& dest)
{
ifstream istr;
int temp;
istr.open(fileName.c_str());
if (istr.fail()) {
throw exception();
}
while (istr >> temp) {
dest.push_back(temp);
}
}
int main(int argc, char** argv)
{
vector<int> myInts;
const string fileName = "test.txt";
try {
readIntegerFile(fileName, myInts);
} catch (const exception& e) {
cerr << "Unable to open file " << fileName << endl;
exit (1);
}
for (size_t i = 0; i < myInts.size(); i++) {
cout << myInts[i] << " ";
}
cout << endl;
return (0);
}
handles errors during input and output
#include <fstream>
#include <iostream>
#include <process.h>
using namespace std;
const int MAX = 1000;
int buff[MAX];
int main(){
for(int j=0; j<MAX; j++)
buff[j] = j;
ofstream os;
os.open("a:edata.dat", ios::trunc | ios::binary);
if(!os){
cerr << "Could not open output file\n"; exit(1);
}
os.write( reinterpret_cast<char*>(buff), MAX*sizeof(int) );
if(!os){
cerr << "Could not write to file\n"; exit(1);
}
os.close();
for(int j=0; j<MAX; j++)
buff[j] = 0;
ifstream is;
is.open("a:edata.dat", ios::binary);
if(!is){
cerr << "Could not open input file\n"; exit(1);
}
is.read( reinterpret_cast<char*>(buff), MAX*sizeof(int) );
if(!is){
cerr << "Could not read from file\n"; exit(1);
}
for(int j=0; j<MAX; j++){
if( buff[j] != j ){
cerr << "\nData is incorrect\n";
exit(1);
}
}
return 0;
}
Read a file in try catch block
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
try{
char buffer[256];
ifstream myfile ("test.txt");
while (! myfile.eof() )
{
myfile.getline (buffer,100);
cout << buffer << endl;
}
}catch(...){
cout << "There was an error !\n";
}
return 0;
}
This outputting a line.
throw exception in function cascading
#include <fstream>
#include <iostream>
#include <stdexcept>
using namespace std;
void funcOne() throw(exception);
void funcTwo() throw(exception);
int main(int argc, char** argv)
{
try {
funcOne();
} catch (exception& e) {
cerr << "Exception caught!\n";
exit(1);
}
return (0);
}
void funcOne() throw(exception)
{
string str1;
string* str2 = new string();
try {
funcTwo();
} catch (...) {
delete str2;
throw; // rethrow the exception
}
delete str2;
}
void funcTwo() throw(exception)
{
ifstream istr;
istr.open("filename");
throw exception();
istr.close();
}