views:

743

answers:

2

Hi,

Using this code:

#include <fstream>

#include <boost/archive/text_oarchive.hpp>

using namespace std;

int main()
{
    std::ofstream ofs("c:\test");
    boost::archive::text_oarchive oa(ofs);
}

I'm getting an unhandled exception at runtime on executing the boost archive line:

boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::archive::archive_exception> >
+1  A: 

You need to catch the exception and then examine its exception_code to see what the root cause is.

paxdiablo
+3  A: 

The following line is in error:

 std::ofstream ofs("c:\test");

The compiler would've spit out a warning (at least) if your file was called jest; but '\t' -- being the escape for inserting a tab, your error goes by uncaught. In short, the file will not be created. You can test this with:

if (ofs.good()) { ... }

Now, since the file was not created, you don't have a valid iterator to pass on to boost::archive::text_oarchive which throws the exception.

Try this:

std::ofstream ofs("c:\\test");
//                  --^ (note the extra backslash)
if (ofs.good()) {
    boost::archive::text_oarchive oa(ofs);
    // ...
}

Hope this helps!

PS: A final nit I couldn't stop myself from making -- if you are going to use

using namespace std;

then

ofstream ofs("c:\\test");

is good enough. Of course, it is not an error to qualify ofstream, but it would not be the best coding style. But then, you know using using namespace is bad, don't you?

PPS:Thank you -- sharptooth for reminding me that \t gets you a tab!

dirkgently
\t is horizontal TAB, so the compiler is very very unlikely to feel the smell.
sharptooth
Bang on! Thanks sharptooth.
dirkgently
You could also just use c:/test - the forward slash works on both Windows and Unix systems as a path separator and doesn't need to be quoted.
Ferruccio
Sure. Very few use it though on Windows.
dirkgently
Thanks, I very quickly figured it out after catching the exception (please excuse my asking this question, it had been a long day), but nonetheless there are some useful tips there, so thanks. I'm curious though, why is using namespace bad?
Dan
The `using namespace std' dumps all symbols in the std namespace to the global namespace causing pollution. Look up namespace pollution.
dirkgently