ofstream error conditions

J

jois.de.vivre

Hi,

I'm trying to write to an ofstream, and for some reason it fails. I
know I can check it with fail() or bad(), but it gives me no useful
information as to why it fails. Are there any C++ functions that do
this or is there any way I can check manually?

Thanks,

Prashant
 
P

Peter Julian

Hi,

I'm trying to write to an ofstream, and for some reason it fails. I
know I can check it with fail() or bad(), but it gives me no useful
information as to why it fails. Are there any C++ functions that do
this or is there any way I can check manually?

Thanks,

Prashant

Its your responsability to check for errors and your choice what error you
actually check for. I gave my crystal ball away and my ESP levels are very
low. So without any code you are basicly on your own.
 
P

Peter Julian

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::eek:fstream 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.

*/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top