Reading in 4 bytes at a time

前端 未结 5 1379
暗喜
暗喜 2021-01-05 01:54

I have a big file full of integers that I\'m loading in. I\'ve just started using C++, and I\'m trying out the filestream stuff. From everything I\'ve read, it appears I c

5条回答
  •  囚心锁ツ
    2021-01-05 02:13

    To read by 4 bytes from ifstream you could overload operator>> as follows (it is actually a partial specialization of the basic_istream class template so istream_iterator could use operator>> from it. Class basic_ifstream is used here to inherit all input file stream functionality from it):

    #include 
    
    typedef unsigned int uint32_t;    
    struct uint32_helper_t {};
    
    namespace std {
    template
    class basic_istream : public basic_ifstream {
    public:
        explicit basic_istream(const char* filename, 
            ios_base::openmode mode ) : basic_ifstream( filename, mode ) {}
    
        basic_istream& operator>>(uint32_t& data) {
            read(&data, 1);
            return *this;
        }
    };
    } // namespace std {}
    

    Then you could use it in the following way:

    std::basic_istream my_file( FILENAME, std::ios::in|std::ios::binary );
    // read one int at a time
    uint32_t value;
    my_file >> value;
    
    // read all data in file
    std::vector data;
    data.assign( std::istream_iterator(my_file),
      std::istream_iterator() );
    

提交回复
热议问题