Load binary file using fstream

后端 未结 4 1919
遇见更好的自我
遇见更好的自我 2021-01-01 06:28

I\'m trying to load binary file using fstream in the following way:

#include 
#include 
#include 
#include         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-01 07:12

    A different way to do the same as Alexey Malistov's answer:

    #include 
    #include 
    #include 
    #include 
    
    struct rint // this class will allow us to read binary
    {
      // ctors & assignment op allows implicit construction from uint
      rint () {}
      rint (unsigned int v) : val(v) {}
      rint (rint const& r) : val(r.val) {}
      rint& operator= (rint const& r) { this->val = r.val; return *this; }
      rint& operator= (unsigned int r) { this->val = r; return *this; }
    
      unsigned int val;
    
      // implicit conversion to uint from rint
      operator unsigned int& ()
      {
        return this->val;
      }
      operator unsigned int const& () const
      {
        return this->val;
      }
    };
    
    // reads a uints worth of chars into an rint
    std::istream& operator>> (std::istream& is, rint& li)
    {
      is.read(reinterpret_cast(&li.val), 4);
      return is;
    }
    
    // writes a uints worth of chars out of an rint
    std::ostream& operator<< (std::ostream& os, rint const& li)
    {
      os.write(reinterpret_cast(&li.val), 4);
      return os;
    }
    
    int main (int argc, char *argv[])
    {
      std::vector V;
    
      // make sure the file is opened binary & the istream-iterator is
      // instantiated with rint; then use the usual copy semantics
      std::ifstream file(argv[1], std::ios::binary | std::ios::in);
      std::istream_iterator iter(file), end;
      std::copy(iter, end, std::back_inserter(V));
    
      for (int i = 0; i < V.size(); ++i)
        std::cout << std::hex << "0x" << V[i] << std::endl;
    
      // this will reverse the binary file at the uint level (on x86 with
      // g++ this is 32-bits at a time)
      std::ofstream of(argv[2], std::ios::binary | std::ios::out);
      std::ostream_iterator oter(of);
      std::copy(V.rbegin(), V.rend(), oter);
    
      return 0;
    }
    

提交回复
热议问题