本文介绍了使用fstream加载二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 c>

  • 定义全局运算符> ;> 会导致与类成员 operator>> 之间的编译时冲突。

  • 为 uint32_t 类型指定 basic_istream 。但是对于专业化,你应该重写 basic_istream 类的所有功能。您可以定义虚拟类 x 并专门化 basic_istream ,如下面的代码:

    1. istream_iterator wants basic_istream as argument.
    2. It is impossible to overload operator>> inside basic_istream class.
    3. Defining global operator>> will lead to compile time conflicts with class member operator>>.
    4. You could specialize basic_istream for type uint32_t. But for specialization you should rewrite all fuctionons of basic_istream class. Instead you could define dummy class x and specialize basic_istream for it as in the following code:



    using namespace std;
    
    struct x {};
    namespace std {
    template<class traits>
    class basic_istream<x, traits> : public basic_ifstream<uint32_t>
    {
    public:
        explicit basic_istream<x, traits>(const wchar_t* _Filename,
            ios_base::openmode _Mode,
            int _Prot = (int)ios_base::_Openprot) : basic_ifstream<uint32_t>( _Filename, _Mode, _Prot ) {}
    
        basic_istream<x, traits>& operator>>(uint32_t& data)
        {
            read(&data, 1);
            return *this;
        }
    };
    } // namespace std
    
    int main()
    {
        basic_istream<x> file( "somefile.dat", ios::in|ios::binary );
        vector<uint32_t> buffer;
        buffer.assign( istream_iterator<uint32_t, x>( file ), istream_iterator<uint32_t, x>() );
        cout << buffer.size() << endl;
        return 0;
    }
    

    这篇关于使用fstream加载二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-22 19:08
    查看更多