<jo***********@gmail.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
Okay thanks, I discovered perror() works with C++ as well!
In the case you prefer a C++ alternative:
Why not use try-catch blocks and std::exceptions to both generate error
messages and modify the execution path of the program?
// Filer.cpp
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <stdexcept>
int main()
{
std::string s_file("data.dat");
std::ofstream ofs;
std::ifstream ifs;
std::string s_buffer;
std::vector<std::string> vs;
try
{
// open file with output file stream,
// check for failure, otherwise write to it, close the ofs
ofs.open(s_file.c_str());
if (!ofs)
{
throw std::exception("(ofstream) error while opening file.");
}
for (int i = 0; i < 10; ++i)
{
ofs << "string " << i << std::endl;
}
ofs.close();
// open file with input file stream, read lines into vector
ifs.open(s_file.c_str());
if (!ifs)
{
throw std::exception("(ifstream) error while opening file.");
}
while (std::getline(ifs, s_buffer)) // getline until failure
{
vs.push_back(s_buffer);
}
if (!ifs.eof()) // if failure was not an eof marker, throw
{
throw std::exception("error while reading file.");
}
// display collected strings by iterating through vector
typedef std::vector<std::string>::iterator VITER;
for (VITER it = vs.begin(); it != vs.end(); ++it)
{
std::cout << *it << std::endl;
}
} // end of try block
catch (const std::exception& e)
{
std::cout << "Exception caught !!\n";
std::cout << e.what() << std::endl;
} // catch
return 0;
} // main
/*
string 0
string 1
string 2
string 3
string 4
string 5
string 6
string 7
string 8
string 9
if you write-protect data.dat, you'ld see the following message:
Exception caught !!
(ofstream) error while opening file.
*/