我正在使用 boosts 序列化函数将数据序列化并保存到项目中的外部文件,然后能够再次读取它们。
我遇到的问题是,如果(错误地)以不正确的格式读入文件,则程序会崩溃(可能是预期的)。
如何识别文件格式错误并在程序崩溃前中断读入过程?
编辑:
我已经在我的读入函数中尝试了一个 try catch 结构,看起来像这样
int read_binary(file_in_out* object){
std::ifstream ifs((*object).file.c_str());
try
{
boost::archive::binary_iarchive ia(ifs);
ia >> (*object).content;
}
catch (boost::archive::archive_exception& ex)
{
std::cout << "An exception occurred. Exception Nr. " << '\n';
return 1;
}
catch (int e)
{
std::cout << "An exception occurred. Exception Nr. " << e << '\n';
return 1;
}
return 0;
}
当文件与它试图读入的结构无关时,这会捕获异常。但是,当我使用过时的版本时,它不会捕获异常并在“ia >> (*object).content;”行崩溃有什么想法吗?
最佳答案
它不应该崩溃。如果是,请向库开发人员报告错误。
不过,它应该引发异常。因此,您可以 try catch 存档异常:
http://www.boost.org/doc/libs/1_36_0/libs/serialization/doc/exceptions.html
unregistered_class, // attempt to serialize a pointer of an
// an unregistered class
invalid_signature, // first line of archive does not contain
// expected string
unsupported_version, // archive created with library version subsequent
// to this one
pointer_conflict // an attempt has been made to directly serialize
// an object after having already serialized the same
// object through a pointer. Were this permitted,
// it the archive load would result in the creation
// of extraneous object.
incompatible_native_format, // attempt to read native binary format
// on incompatible platform
array_size_too_short, // array being loaded doesn't fit in array allocated
stream_error // i/o error on stream
invalid_class_name, // class name greater than the maximum permitted.
// most likely a corrupted archive or an attempt
// to insert virus via buffer overrun method.
unregistered_cast // base - derived relationship not registered with
// void_cast_register
此外,捕获 std::exception&
例如bad_alloc
, range_error
等
关于c++ boost序列化如何防止不正确的文件崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25649998/