与 Alexey Malistov 的回答相同的另一种方法:
#include <fstream>
#include <iterator>
#include <vector>
#include <iostream>
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<char*>(&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<const char*>(&li.val), 4);
return os;
}
int main (int argc, char *argv[])
{
std::vector<int> 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<rint> 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<rint> oter(of);
std::copy(V.rbegin(), V.rend(), oter);
return 0;
}