c++ boost序列化如何防止不正确的文件崩溃

标签 c++ serialization boost

我正在使用 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/

相关文章:

c++ - 如何声明 vector::size_type 的 vector ?

java - Jackson - 将 Map 实现反序列化为 HashMap

c# - XmlArrayAttribute 和 XmlArrayItemAttribute 有什么区别?

javascript - 使用 AJAX 序列化日期

c++ - RegExp 查找不以特定单词结尾的特定字符串

c++ - C++ 中的多个整数类型类

c++ - 将指针从 C++ 传递到 Python/w boost python?

c++ - 为什么两个几乎相同的实现有很大的执行时间差异?

c# - 如何在 C# 中映射双 C 结构指针?

c++ - 在回调中将指针转换为 vector 类型